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?
CodePudding user response:
The useState hook is somewhat asynchronous (although you cannot wait
for it).
Try using a useEffect:
useEffect(() => {
console.log(isEnabled)
}, [isEnabled]) // Array of dependencies: when any of these value changes, the function in the useEffect will re-run
More information here:
- https://dev.to/shareef/react-usestate-hook-is-asynchronous-1hia
- https://javascript.plainenglish.io/why-you-shouldnt-always-use-usestate-658994693018
CodePudding user response:
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 before console.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 component SetupSwitch
is re-rendered when the state isEnabled
is updated, which means it prints the console.log of the updated variable again.
...
console.log(isEnabled);
const Change = () => {
...