0

This is my code:

const [address, setAddress] = useState("1");

const updateData = () => {
    setAmount("2");
    console.log(address);
}

After updateData, why printed 1? I changed it to 2.

ali
  • 55
  • 1
  • 6

1 Answers1

1

Setting the state in React acts like an async function.
Meaning that the when you set the state and put a console.log right after it, it will likely run before the state has actually finished updating.

Which is why we have useEffect, a built-in React hook that activates a callback when one of it's dependencies have changed.

Example:

useEffect(() => {
   console.log(address)
   // Whatever else we want to do after the state has been updated.
}, [address])

This console.log will run only after the state has finished changing and a render has occurred.

  • Note: "address" in the example is interchangeable with whatever other state piece you're dealing with.

Check the documentation for more info about this.

tomleb
  • 2,409
  • 2
  • 9
  • 24
  • Thank you. Can I use await? `await setAddress("2");` or `setTimeOut`? – ali Sep 12 '22 at 07:16
  • Just FYI setting state in React isn't anything at all like an async function. The `setState` function is complete synchronous. It enqueues an update to be processed later. Think of it more like a request to update state. – Drew Reese Sep 12 '22 at 07:36
  • @ali No, `setAmount` isn't an `async` function nor does it return a Promise, so there's nothing to `await` nor will any amount of `setTimeout` in the callback function scope change the value of `address` as it's a Javascript closure over the `address` value when the function was invoked. – Drew Reese Sep 12 '22 at 07:38