Since React version 16.8, function components have been given more functionality than just simple logic components. Added low-level API hook child nodes of the useXX series. Let function components and class components share the world equally.

setState

  • What does setState do?

    • Class component status update function, will be on the componentstateObject schedules an update
  • Is setState synchronous or asynchronous?

    • In different execution contexts,setStateIn different ways
      • Asynchronous: Update state multiple times, merging multiple updates into one
        • In the life cycle function and composition function
      • Synchronization: Needs to get its updated value immediately
        • setTimeout
        • Native events
        • Async function

useState

  • What does useState do?

    • Provides definable, modifiable sets of state values for function components
  • Is the syntax of useState deconstruction?

    • Code sample
    function Demo (props) {
        const [count, setCount] = useState(0); // Do you want to deconstruct the syntax?
    }
    Copy the code
    • After the useState function is executed, it initializes the default value and returns an array. The first array is the value of the state, and the second array is the method to change the state.
  • UseState uses the initial value to create the state, but only once. Why?

    • When the useState command is executed, the system checks whether data already exists in the status data
    • If the current data state reference is queried and data with subscript 0 already exists, it does not reuse the original value to generate data
  • The second value returned by useState, the function that sets the state, is synchronous or asynchronous?

  • Why can’t useState be written in a judgment and loop?

    • The hooks nodes are stored as linked lists
    • The state of useState is executed in a fixed order
    • Judging and looping can cause it to be out of order, and operations that need to read state can cause problems
  • Does a change in the state of useState necessarily cause component updates?

    • Using the function that updates the data, a shallow comparison is made to the updated state data. If the updated data is directly compared to the same underlying data type or the same address type, the component will not render
  • UseState update function, can use async?

    • Yes, you need to wrap a layer of functions