I’m having trouble with React Native showing wrong value for me. I wan’t to show the value after an useState update. My goal is to pass the value to the parent component but right now it passes the opposite value (true when switch is off). What do I have to do to console.log the right value after a useState update?
Question posted in React native
The official React Native documentation can be found here.
The official React Native documentation can be found here.
4
Answers
The useState hook is somewhat asynchronous (although you cannot
wait
for it).Try using a useEffect:
More information here:
State updates in React are asynchronous, meaning that React does not wait for the state to be updated before executing the next line of code. In your case, the state update
setIsEnabled(...)
is not finished beforeconsole.log(isEnabled)
is run, and therefore it returns the old value.Just put the
console.log(isEnabled)
outside the function for it to print the update correctly. The componentSetupSwitch
is re-rendered when the stateisEnabled
is updated, which means it prints the console.log of the updated variable again.You will have to implement
useEffect
to view the changes.useState
is an asynchronous function it will go to the callback queue, meanwhile, the value will be consumed, so you need to trigger the action whenever thecount
changes. (for this example)The
Change
function will always "see" the state value that existed at the time of running the function. This is not because of asynchronicity per se (state updates are actually sync) but because of how closures work. It does feel like it is async though.The state value will properly update in the background, but it won’t be available in the "already-running" function. You can find more info here.
The way I see your handler implemented though:
I recommend this as this way you will notify the parent immediately on user click instead of waiting for the state to be set and then notifying the parent in the next render cycle (in the effect), which should be unnecessary.