0

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.

four-eyes
  • 10,740
  • 29
  • 111
  • 220

1 Answers1

1

Your code does not match your text

You say,

However, before calling _doSomethingWithCount() I set the state. In this case, I increase the counter by 1.

But your code says,

    _doSomethingWithCount();
    setCounter(counter + 1);

If you do what your text says...

then counter will have its new value when _doSomethingWithCount runs.

If you do what your code says...

then counter will have its old value when _doSomethingWithCount runs.

Either way, there is no race.

At the point in the code where you call _doSomethingWithCount, that function will run, and the value of counter at that time will be determined by whether the setCounter() is above or below the function call, in your code.

ProfDFrancis
  • 8,816
  • 1
  • 17
  • 26