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?
const [myState, setMyState] = useState(false)

setMyState(true)
console.log(myState) // this is not guaranteed to return true
const [myState, setMyState] = useState(false)

setMyState(true)
console.log(myState) // this is not guaranteed to return true
11 Replies
stoyko
stoyko2y ago
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
barry
barry2y ago
You cant, best you can do is figure out what the next value is and just use that
riccardolardi
riccardolardiOP2y ago
@barry thanks. Ugly hack would be to use a setTimeout to bypass react state update cycle
barry
barry2y ago
Wouldn't work
riccardolardi
riccardolardiOP2y ago
why?
barry
barry2y ago
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
riccardolardi
riccardolardiOP2y ago
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
bruno!
bruno!2y ago
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
z
z2y ago
I maybe wrong, but i think you can use useEffect to look for value change in myState and then run ur func accoringly?
King_codes
King_codes2y ago
Isnt this solved via adding that state as a dependency to another useCallback function?
Want results from more Discord servers?
Add your server