react
react copied to clipboard
Bug: useState apply updaters order does not comply with the documentation
React version: 16 & 18
Steps To Reproduce
- Call setState(functional updater) twice
- One of the updater will be calculated before re-render.
Link to code example: https://codesandbox.io/p/sandbox/quizzical-hugle-wsp7zh
The expected behavior
As per the documentation of setState,
If you pass a function as nextState, it will be treated as an updater function. It must be pure, should take the pending state as its only argument, and should return the next state. React will put your updater function in a queue and re-render your component. During the next render, React will calculate the next state by applying all of the queued updaters to the previous state.
Expected behaviour is,
- click on the button
- enqueue two updater actions
- the App component re-renders
- (when visiting useState) apply two actions
- get the updated new value
The current behavior
However the current behavior is,
- click on the button
- one of the actions is calculated IMMEDIATELY, the rest are enqueued.
- the App component re-renders
- (when visiting useState) apply the remaining actions
- get the updated new value
Note
Only the first time not complying. From the second time it works expectedly.