How React Hooks work

Most of our React components can save state, but functional components cannot? And class components have a life cycle, but functional components cannot?

In the early version of React, class components can optimize some unnecessary rendering by inheriting PureComponent. Compared with functional components, React's official website does not provide a corresponding method to cache function components to reduce unnecessary rendering. The React.memo function directly out of 16.6 .
The new Hook of React 16.8 allows React functional components to have state and provides life cycle methods like componentDidMount and componentDidUpdate .
Hooks do not replace classes, they are just a new tool you can use.

Examples of Hooks:

OneTimeButton is a functional component, what it does is to call the sayHi method when we click the functional component

import React from 'react';
import {
    
     render } from 'react-dom';

function OneTimeButton(props) {
    
    
  return (
    <button onClick={
    
    props.onClick}>
        点我
    </button>
  )
}

function sayHi() {
    
    
  console.log('yo')
}

render(
  <OneTimeButton onClick={
    
    sayHi}/>,
  document.querySelector('#root')
)

What this component does is keep track of whether it is clicked, and if it is clicked, disable the button, just like a one-time switch.

But it needs a state, because it is a function, it cannot have a state (before React 16.8), so it needs to be restructured into classes.

class OneTimeButton extends React.Component {
    
    
  state = {
    
    
    clicked: false
  }

  handleClick = () => {
    
    
    this.props.onClick();

    // Ok, no more clicking.
    this.setState({
    
     clicked: true });
  }

  render() {
    
    
    return (
      <button
        onClick={
    
    this.handleClick}
        disabled={
    
    this.state.clicked}
      >
        You Can Only Click Me Once
      </button>
    );
  }
}

Use Hook to add State

Use the new useState hook to add state to ordinary function components:

import React, {
    
     useState } from 'react'

function OneTimeButton(props) {
    
    
  const [clicked, setClicked] = useState(false)
  
  function doClick() {
    
    
    props.onClick();
    setClicked(true)
  }

  return (
    <button
      onClick={
    
    clicked ? undefined : doClick}
      disabled={
    
    clicked}
    >
      点我
    </button>
  )
}

useState is a hook. Its name starts with "use" (this is one of Hooks' rules-their name must start with "use" ).

The parameter of the useState hook is the initial value of the state and returns an array containing two elements : the current state and a function to change the state.

The class component has a large state object, and a function this.setState changes the entire state object at once.

Function components have no state at all , but the useState hook allows us to add small blocks of state when needed . Therefore, if only a boolean is needed, we can create some state to save it.

Since Hook creates these states in a special way, and there is no setState function to change the state in the function component, Hook needs a function to update each state. So the useState return is a pair of correspondence: a value, a function to update the value. Of course, the value can be anything-any JS type-numbers, booleans, objects, arrays, etc.

Features of Hooks

Calling order rules (they must be called in the same order each time);

Assume the following components:

function AudioPlayer() {
    
    
  const [volume, setVolume] = useState(80);
  const [position, setPosition] = useState(0);
  const [isPlaying, setPlaying] = useState(false);
  .....
}

It calls useState 3 times, and React will put these three hooks into the Hooks array during the first rendering.

Next time you render, the same 3 hooks are called in the same order, so React can look at its array and find that there is already a useState hook at position 0, so React will not create a new state, but return to the existing one. status.

This is how React can create and maintain state in multiple function calls, even if the variable itself goes out of scope every time.

Hooks rules

Custom hooks functions only need to comply with Rule 3: Their names must be prefixed with " use ".

function AudioPlayer() {
    
    
  // Extract these 3 pieces of state:
  const [volume, setVolume] = useState(80);
  const [position, setPosition] = useState(0);
  const [isPlaying, setPlaying] = useState(false);

  // < beautiful audio player goes here >
}

Create a new function that specializes in these states, and use some additional methods to return an object to make it easier to start and stop playback, for example:

function usePlayerState(lengthOfClip) {
    
    
  const [volume, setVolume] = useState(80);
  const [position, setPosition] = useState(0);
  const [isPlaying, setPlaying] = useState(false);

  const stop = () => {
    
    
    setPlaying(false);
    setPosition(0);
  }

  const start = () => {
    
    
    setPlaying(true);
  }

  return {
    
    
    volume,
    position,
    isPlaying,
    setVolume,
    setPosition,
    start,
    stop
  };
}

One advantage of extracting state in this way is that related logic and behavior can be combined . A set of state and related event handlers and other update logic can be extracted, which not only cleans up the component code , but also makes these logic and behaviors reusable.

By calling custom hooks in custom hooks, hooks can be combined.

Hooks are just functions. Of course, functions can call other functions.

Hooks provide a new way to deal with problems in React, and the ideas in it are very interesting and novel.

Guess you like

Origin blog.csdn.net/Menqq/article/details/111825252