React Hooks?
Hook is a new feature in React 16.8. It lets you use state and other React features without having to write a class.
As anyone who has used React knows, there are two types of components in React: functional components and class components. Prior to Act 16.8, functional components could not play with ref and state, or even life cycles, mainly because functional components did not have the concept of this, whereas state, ref, life cycle functions, and so on were mounted on the component itself. So many people choose to use class components. React16.8 added Hooks to enhance functional components, introducing a series of Hooks to improve the functionality of functional components.
Which Hooks are available and how to use them?
Here are some Hooks that are frequently used. See the React Documentation for the rest.
React Hooks All start with use. They are JavaScript functions.
1 > useState -> state hook
state
React is an important property of the React component, used to record statesetState
Method updates state and view.
Let’s first look at how state is used in class components:
Class component
import React, { Component } from 'react'
export default class RClassComp extends Component {
state = {
account: ' '.age: 0
}
handleClick = () = > {
this.setState({
account: 'CoCoyY1'.age: 18
});
}
render() {
return (
<>
<div>Name: {this. State. The account}</div>
<div>Age: {this. State. The age}</div>
<button onClick={this.handleClick}>Am I</button>
</>)}}Copy the code
Effect:
Use state in functional components:
Using the useState Hook allows us to useState in a functional component. The useState method takes an initial value and returns an array with state as the first item and the set method for that state as the second item.
Used in functional components
import React, { useState } from 'react';
export default() = > {const [obj, setObj] = useState({account: ' '.age: 0});
const handleClick = () = > {
setObj({
account: 'CoCoyY1'.age: 18
});
}
return (
<>
<div>----RFC----</div>
<div>Name: {obj. Account}</div>
<div>Age: {obj. Age}</div>
<button onClick={handleClick}>Am I</button>
</>)}Copy the code
Effect:
2 > useRef -> ref hook
The ref attribute is used to get the exact node of a component or element. React is not officially recommended, but it is a very common attribute.
Use ref in class components:
There are three ways to use a REF in a class component:
(1) Use a string;
(2) Use arrow function (I often use);
(3) Use createRef method; -> This method takes the current attribute;
Type of component
import React, { Component } from 'react'
export default class RClassComp extends Component {
state = {
account: ' '.age: 0
}
handleClick = () = > {
const accountValue = this.inputEl.value;
this.setState({
account: accountValue,
age: 18
});
}
render() {
return (
<>
<div>Name: {this. State. The account}</div>
<div>
<input ref={c= > this.inputEl = c} type="text" />
</div>
<div>Age: {this. State. The age}</div>
<button onClick={this.handleClick}>Am I</button>
</>)}}Copy the code
Effect:
Use ref in functional components:
Using the useRef Hook allows us to useRef in a functional component in a manner similar to the createRef method in a class component.
Functional component
import React, { useState, useRef } from 'react';
export default() = > {const [obj, setObj] = useState({account: ' '.age: 0});
const inputEl = useRef();
const handleClick = () = > {
const accountValue = inputEl.current.value;
setObj({
account: accountValue,
age: 18
});
}
return (
<>
<div>----RFC----</div>
<div>Name: {obj. Account}</div>
<div>
<input ref={inputEl} type="text" />
</div>
<div>Age: {obj. Age}</div>
<button onClick={handleClick}>Am I</button>
</>)}Copy the code
Effect:
3 > useEffect -> Lifecycle of functional components
In a specific project, we often use lifecycle functions to send requests or to set up something to listen on.
Common lifecycle functions are:
(1) componentDidMount;
(2) componentDidUpdate;
(3) componentWillUnmount;
Use lifecycle functions in class components:
Type of component
import React, { Component } from 'react'
export default class RClassComp extends Component {
state = {
count: 0,}componentDidMount() {
this.timer = setInterval(() = > {
this.setState((state) = > ({count: state.count + 1}));
}, 1000);
};
componentDidUpdate(preProps, preState) {
if(preState.count >= 5) {
this.setState({count: 0}); }}componentWillUnmount() {
clearInterval(this.timer);
}
render() {
return (
<>
<div>The current count is: {this.state.count}</div>
</>)}}Copy the code
Effect:
Using lifecycle functions in functional components:
The useEffect hook of functional components can be seen as the integration of the above three life cycles. UseEffect takes two arguments, the first a function and the second an array. The callback is called once (equivalent to componentDidMount) when the component has just been mounted, and the return value of that callback is also a function, The returned function is called before the component is destroyed (equivalent to componentWillUnmount), but the effect cleanup phase is executed every time the component is rerendered, not just once when the component is uninstalled. The second argument represents a list of objects to listen to. If the second argument is not passed, Defaults to listening for all variable changes, that is, each variable change executes the body of the first parameter (equivalent to componentDidUpdate). Passing an empty array does not listen for any variables. UseEffect can be used multiple times.
In functional components
import React, { useState, useEffect } from 'react';
export default() = > {const [count, setCount] = useState(0);
let timer;
useEffect(() = > {
if(timer) {
return;
}
if(count > 5) {
setCount(0);
}
timer = setInterval(() = > {
setCount(count + 1);
}, 1000);
return () = > {
clearInterval(timer);
};
}, [count]);
return (
<>
<div>----RFC----</div>
<div>Current count: {count}</div>
</>)}Copy the code
Effect:
Why use React Hooks?
(1) It is difficult to reuse state logic between components -> Use custom hooks to implement reuse state, instead of using complex and cumbersome methods such as render props and higher-order components.
(2) Complex components become difficult to understand -> Different lifecycle functions are written too dispersively, and hooks break the interrelated parts of components into smaller functions.
(3) The unintelligible class -> requires constant attention to maintain and bind this, which makes component writing need to be careful.
(4) Class also poses some problems for current tools.
Using the hooks of vue, we can enable the function component to have the three major attributes and the lifecycle functions of the class component. This is not needed. The most obvious change to the coding process is to no longer use this. After getting used to using class components, it feels awkward to write functional components, but after using it for a long time, it is really delicious.
Write it at the end (^.^)
If you think my writing is good, you can give me a thumbs up
If there is a wrong place, write bad place also please point out, for me to correct.
I’m CoCoyY1, a front-end enthusiast for documenting your learning.
My other articles
The Expose function in Vue3———— controls the object content exposed when the component is ref
Vue3 new syntax sugar — Setup script———— makes vue3 setup writing easier, with components free of registration and variables free of return