- The change of state state in the function component is stored by calling Hook useState; - The update store is made by calling setState in the class componentCopy the code

setState

usesetStateThe reason why

There is no way to update the interface directly by changing the value of state during development

  • Modify thestateAfter that, React is expected based on the lateststateRerender the page, but this way,ReactDon’t knowstateThe change, also can’t re-render;ReactIs not similar toVue2In theObject.definePropertyorVue3In theProxyTo monitor changes in data; Therefore, setState must be used to tell React that the data has changed.

setStateImplementation call of

  • setStateMethods fromComponentClass inherited from

Asynchronously updatedsetState

  • The reason for the asynchronous update

    • Performance can be significantly improved: if every call is re-rendered by the interface, it is very inefficient to get multiple updates and then batch them
    • If state is updated synchronously but the render function is not executed, state and props cannot be aligned, which can cause many development problems
  • Gets the result of the asynchronous update

    • SetState callback: setState(newState, callback) takes two arguments, and the callback is executed after the state update.
    • ComponentDidUpdate Life cycle function
  • Is setState necessarily asynchronous? There are actually two outcomes

    • Asynchronous: within the component’s lifetime or in events synthesized by React

    • Synchronization: in setTimeout or native DOM events

    Note: 'in setTimeout or native DOM events' why is the setState operation synchronous? fCopy the code
  • SetState merger

    • Merge of setState. It can be seen from the source code that setState will merge the last state object with the current incoming state

    • Multiple call merging: when setState is called for multiple times, only the last state will take effect (each call of setState is equivalent to calling the render function for a page redrawing rendering, and multiple call of setState merging can avoid frequent page rendering, which is conducive to performance optimization)

useState

UseState implementation call