Assuming I have a function (_onClick()
) which is called on every click, which calls another function _doSomethingWithCount()
. However, after calling _doSomethingWithCount()
I set the state. In this case, I increase the counter
by 1
.
const Foo = () => {
const [counter, setCounter] = useState(0);
const _onClick = () => {
_doSomethingWithCount();
setCounter(counter + 1);
}
const doSomethingWithCount = () => {
console.log(counter)
}
return (
<button onClick={() => _onClick()}>Click Me</button>
)
}
Will the console.log()
in doSomethingWithCount()
always log the value of count before I called setCounter(counter + 1);
thus the "old" value? Or will doSomethingWithCount()
wait until the state
is set because it relies on a variable from the state? Or is there some sort of "race" going on. If the state
is set faster than JS can execute doSomethingWithCount()
, doSomethingWithCount()
will sometimes have the update count
.