react icon indicating copy to clipboard operation
react copied to clipboard

Bug: useState apply updaters order does not comply with the documentation

Open gwy15 opened this issue 2 months ago • 2 comments

React version: 16 & 18

Steps To Reproduce

  1. Call setState(functional updater) twice
  2. 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,

  1. click on the button
  2. enqueue two updater actions
  3. the App component re-renders
  4. (when visiting useState) apply two actions
  5. get the updated new value

The current behavior

However the current behavior is,

  1. click on the button
  2. one of the actions is calculated IMMEDIATELY, the rest are enqueued.
  3. the App component re-renders
  4. (when visiting useState) apply the remaining actions
  5. get the updated new value

image

Note

Only the first time not complying. From the second time it works expectedly. image

gwy15 avatar Dec 04 '24 09:12 gwy15