You can use useEffect
to access the latest state after updating it. If you have multiple state hooks and would like to track the update on only part of them, you can pass in the state in an array as the second argument of the useEffect
function:
useEffect(() => { console.log(state1, state2)}, [state1])
The above useEffect
will only be called when state1
is updated and you shouldn’t trust the state2
value from inside this function as it may not be the latest.
If you are curious about whether the update function created by useState
is synchronous, i.e. if React batches the state update when using hooks, this answer provide some insight into it.