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
.
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
.
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.
Check the documentation for more info about this.