The simplest useState implementation
UseState usage
The sample
After clicking button, +1 is executed
Analyze the process
On the first render, render
When the user clicks button, setN(n+1) is called, render ”
Notice that useState(0) is run each time APP() is called, but the n is different each time
A few questions
-
What happens when setN is executed? Does n change? Will App() be re-executed?
Doing setN will re-render the UI, n will not change, App() will re-execute
-
If App() will be reexecuted, then useState(0). Is n going to be different every time
Analysis of the
-
setN
SetN must modify the data state to store n+1 in state
SetN must trigger
re-render -
useState
UseState will definitely read the latest value of n from state
-
state
Each component has its own data state
Try implementing React. UseState
Click to see the code
Declare a variable _state outside myUseState that will not be reset by it
To improve the
What if a component uses two Usestates?
Since all data is placed in _state, there is a conflict
The improvement idea is as follows:
-
Make _state an object
Such as _state = {n: 0, m: 0}
It doesn’t work, because useState(0) doesn’t know whether the variable is called n or m
-
Make _state an array
Such as _state = [0, 0]
Yes, code
_state
Disadvantages of the array scheme
UseState call order —
If n is the first rendering, m is the second, and k is the third
The second rendering must ensure the exact same order
React does not allow the following code
Other problems
-
APP uses _state and index, what do other components use?
Create a _state and index for each component
-
What about the same name in the global scope?
Put it on the virtual node object corresponding to the component
graphic
conclusion
Each function component has a React node that stores state and index. UseState reads state[index], which is determined by the order in which useState appears. SetState modifies state and triggers updates.
Note: This is a simplification of React, the React node should be FiberNode, the real name of _state is memorizedState, and the index implementation uses linked lists.
React Hooks Implement React Hooks
useRef
The sample
Two operations
- Click on the
+ 1
, then clicklog
— No bug, print outn:1
- Click on the
log
, then click+ 1
— If there is a bug, print itn:0
So why log out of old n?
The state of being throughout
There are a number of ways to achieve the state throughout
The global variable
In the window. XXX
useRef
UseRef can be used not only for divs, but also for arbitrary data
useRef
Note: there are no bugs, but {ref.current} cannot be updated in real time
Mandatory update example, not recommended
useContext
UseContext can be used not only throughout, but also across different components
UseContext example