'Why use functions when updating state variable in useState()
const [state, updateState] = useState(0)
updateState(prevState => prevState+1) //Would output to 1
Why is this the recommended way to update states using useState?
updateState(prevState+1) //Would also output 1
Why not this?
I've tried searching for an explanation for this and this is the only one I got
const [state, updateState] = useState(0)
updateState(prevState+1) //Would also output 1
updateState(prevState+1) //Wouldn't output 2, still outputs 1
The explanation I got from this was that the second updateState still references for state with the value of 0
const [state, updateState] = useState(0)
updateState(prevState => prevState+1) //Would output to 1
updateState(prevState => prevState+1) //Would output to 2
But why does this work? What's the underlying mechanism difference between the two?
Thanks!
Solution 1:[1]
React setState updates the state asynchronously and having multiple setState calls can lead to incorrect values as you've written
const [state, updateState] = useState(0)
updateState(prevState+1)
updateState(prevState+1)
updateState(prevState+1)
updateState(prevState+1)
this does not update the value to 4 it stays the on 1 because of batching multiply setState the last updateState will override the other
"React does not guarantee that the state changes are applied immediately"
this is the reason we use the function on setState for getting the previous state before updating it.
updateState(prevState => prevState+1)
updateState(prevState => prevState+1)
updateState(prevState => prevState+1)
updateState(prevState => prevState+1)
this is the safer way.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shambhu Sahu |
