Hooks are new in React 16.8. It lets you use state and other React features without having to write a class.

In short, use Hooks + Function Component instead of Class Component

why Hooks

React provides both Class Component and Function Component. Before Hooks, use Class Component when state is needed; When state is not required, either notation can be used. However, there are the following problems:

Reconstructing a Class Component from a Function Component can be complex

Since the Function Component simply receives props, binds events, and returns JSX, it is itself a stateless Component. With the development of business, when Function Components cannot meet the requirements, they need to be reconstituted into class components, which has a certain degree of complexity. Such as:

The Function Component:

function Hello(props) {
  return (<div>Hello World</div>);
}
Copy the code

The Class Component:

class Hello extends React.Component {
  constructor(props) {
    super(props);
    // ...
  }
  
  render() {
    return (<div>Hello World</div>); }}Copy the code

Class Component is hard to understand

Let’s start with a full example:

class Hello extends React.component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    // ...
  }
  componentWillMount() {
    // ...
  }
  
  componentDidMount() {
    // ...
  }
  
  componentShouldUpdate() {
    // ...
  }
  
  componentWillUnMount() {
    // ...
  }
  
  handleClick() {
    // ...
  }
  
  render() {
    return (<div onClick={this.handleClick}>Hello World</div>); }}Copy the code

In this example, you can see the various lifecycle methods, this, bind. This point bothers a lot of people. Second, the various lifecycle methods can make components bloated and difficult to understand

Reuse state logic between components

React has no good way to “attach” reusability logic to components (e.g., store to components). But we can use render props and HOC. When using render props and HOC, you can see that the component tree is so hierarchical that it’s easy to get into nested hell.

Such as:

/ / component
class Hello extends React.component {}

// Use HOC to add some attributes
const NewHello = simpleHOC(Hello);
Copy the code

In this case, the hierarchy of Hello becomes:

  • simpleHoc wrapper
    • Hello

Hooks make it easy to extract reusable logic and use it in components without needing additional component structures.

Built-in Hooks

Let’s take a look at an example: display the counter, click the button, the counter value +1

function App() {
  // Use 'useState' to define the 'count' variable and get the 'getter' and 'setter'
  const [count, setCount] = useState(0);
  
  / / the other state
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={()= > setCount(count + 1)}>Click me</button>
    </div>
  );
}
Copy the code

As you can see from the example above, use Hooks to separate UI from logic

React has built-in hooks:

  • Basic Hooks
    • UseState: Adds state to the component
    • UseEffect: Adds a side effect to the component that takes effect after render
    • UseContext: Share data across components
  • Additional Hooks
    • UseReducer: Manages complex data structures
    • useCallback
    • UseMemo: Used to cache time-consuming calculation results
    • UseRef: Returns a REF object that remains consistent throughout the life of the component
    • UseImperativeHandle: used with the forwardRef to customize the value exposed by the ref to the parent component
    • UseLayoutEffect: executed before the browser draws the node
    • UseDebugValue: Developer tool debugging

Custom Hooks

The above built-in Hooks can also be wrapped to become a custom Hooks

For example, data can be obtained by ID

function useFetchData(id) {
  const [data, setDate] = useState({});
  
  useEffect(() = > {
    fetch(`https://xxxx/${id}`);
  }, [id]);
  return { data };
}
Copy the code

How do you simulate the life cycle

  • constructor

    Function components do not require constructors. State can be initialized using useState

    const [count, setCount] = use State(0);
    Copy the code
  • componentDidMount

    UseEffect passes the second argument as []

    // ...
    
    useEffect(() = > {
      // need to be executed in componentDidMount} []);// ...
    Copy the code
  • componentDidUpdate

    UseEffect passes in an array with a null or variable second argument

    // ...
    
    useEffect(() = > {
      // ...
    }, [count]); // Update only when count changes
    
    // ...
    Copy the code
  • componentWillUnmount

    UseEffect function returns a function to simulate

    useEffect(() = > {
      return function cleanup() {
        // need to be executed in componentWillUnmount}});Copy the code
  • shouldComponentUpdate

    Wrap a component with react. Memo to perform a shallow comparison of its props

    const Hello = React.memo((props) = > {
      / / component
    });
    Copy the code
  • ComponentDidCatch and getDerivedStateFromError: Not currently supported


Public account: Brush small Q