Adam Kronquist
Adam Kronquist

Reputation: 11

React Native console.log old value useState

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?

Watch image for example here

Upvotes: 0

Views: 2181

Answers (4)

fum4
fum4

Reputation: 297

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:

    const handleChange = () => {
      setIsEnabled(!isEnabled) // you do not need updater function, you can directly reference the state
      triggerParentMethod(!isEnabled); // then you can also directly call the parent function here
    }

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.

Upvotes: 1

Jaisal Shah
Jaisal Shah

Reputation: 331

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 the count changes. (for this example)

const [count, setCount] = useState(0);

useEffect(() => console.log(count), [count]);

setCurrPos(preevCount => prevCount + 1);

Upvotes: 0

user2037443
user2037443

Reputation: 84

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 = () => {
...

Upvotes: 0

Ovidiu Cristescu
Ovidiu Cristescu

Reputation: 1043

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:

Upvotes: 3

Related Questions