well, if you refer to the relevant docs you'll find...

const [state, setstate] = usestate(initialstate);

returns a stateful value, and a function to update it.

during the initial render, the returned state (state) is the same as the value passed as the first argument (initialstate).

the setstate function is used to update the state. it accepts a new state value and enqueues a re-render of the component.


during subsequent re-renders, the first value returned by usestate will always be the most recent state after applying updates.

so your new state, whatever it is, is what you've just set in usestate, i.e. the value of initialstate. it goes directly to state, which updates reactively thereafter. quoting further from the relevant docs:

what does calling usestate do? it declares a “state variable”. our variable is called count but we could call it anything else, like banana. this is a way to “preserve” some values between the function calls — usestate is a new way to use the exact same capabilities that this.state provides in a class. normally, variables “disappear” when the function exits but state variables are preserved by react.

if you'd like to do something whenever your state updates, then just use componentdidupdate.(docs)


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.

Related Query

More Query from same tag