State updates from useState hook not always collapsed?
See original GitHub issueDo you want to request a feature or report a bug? I’m hoping it’s a bug, it at least bit me very unexpectedly when trying out the new react hooks.
What is the current behavior? When multiple setters returned from useState are called in the same timeslice:
- sometimes they are collapsed into a single update, and a single rerender is triggered, the ‘intermediate’ state is not observable
- sometimes they are not collapsed into a single update, and multiple rerenders are triggered, the ‘intermediate’ state is observable from the first rerender
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem.
See https://codesandbox.io/s/74nm51wv00
The toggle
triggered from the button click will collapse the state changes, so the a === b
console.log will never trigger.
However the toggle
triggered from window.setInterval will not collapse the state changes, triggering the console.log.
What is the expected behavior? I would expect the state changes to always be collapsed, a little bit for performance (less rerenders), but mostly because this makes logically ‘impossible’ states observable during rendering, which was very unexpected for me.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React? React 16.7.0-alpha.0 with the new hooks.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:1
- Comments:7 (4 by maintainers)
And of course you can also
useReducer
to describe updates to multiple fields as a result of one dispatch. I’d say we recommend it over multiple state variables when the logic gets complex.Hmm, right. The
ReactDOM.unstable_batchedUpdates
indeed works around my issue, and the way forward with (more) automatic batching would be a perfect fix.