- 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
usesetState
The reason why
There is no way to update the interface directly by changing the value of state during development
- Modify the
state
After that, React is expected based on the lateststate
Rerender the page, but this way,React
Don’t knowstate
The change, also can’t re-render;React
Is not similar toVue2
In theObject.defineProperty
orVue3
In theProxy
To monitor changes in data; Therefore, setState must be used to tell React that the data has changed.
setState
Implementation call of
setState
Methods fromComponent
Class 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