React guarantee updated state variable
I'm setting a state using the setter. In the next line I have a function which relies on the "updated" value of that state. How can I guarantee that value is the updated one and not stale? Since react does some "magic" pooling for state updates / doesn't execute state updates synchronously?
11 Replies
Yes, but you should never do this. Can you provide some working code, that you are working with, so that I can actually see the current use case
You cant, best you can do is figure out what the next value is and just use that
@barry thanks. Ugly hack would be to use a
setTimeout
to bypass react state update cycleWouldn't work
why?
Because it's still the old reference you have
Doesn't matter if it's in a setTimeout, you don't have a getter, only a copy/reference
I see. My usecase is a bit different than in the contrived example I gave. The state is in a context and is checked somewhere else, not directly referenced. It does "seem" to work so far
because where you checked probably is already getting the new reference in a new render cycle
but answering your initial question, just assign the value you'll send to "newState", then use setMyState(newState) and use the new state variable on the rest of the function
https://react.dev/learn/render-and-commit
https://react.dev/learn/state-as-a-snapshot
https://react.dev/learn/queueing-a-series-of-state-updates
Render and Commit – React
The library for web and native user interfaces
State as a Snapshot – React
The library for web and native user interfaces
Queueing a Series of State Updates – React
The library for web and native user interfaces
I maybe wrong, but i think you can use useEffect to look for value change in myState and then run ur func accoringly?
Isnt this solved via adding that state as a dependency to another useCallback function?