Reactjs: update state not show current value on next line

Viewed 23

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.

1 Answers

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.

Related