useState: when to use callback

I am working on the course over useState and useEffect. I get the general premise of the topic at hand. But I caught
myself wondering why the callback function is used in some occasions and not others within the state setter funcitons.

setCount(prevCount => prevCount + 1)

When our state setter calls the callback function, this state setter callback function takes our previous count as an argument. The value returned by this state setter callback function is used as the next value of count (in this case, prevCount + 1).

We can also just call setCount(count +1) and it would work the same in this example, but for reasons that are out of scope for this lesson, it is safer to use the callback method.

I am actually wondering what are the reasons that it is safer to use the callback method… and how should I approach the scenario moving foward?

Not always. If you call setCount very often and in a very short period of time, you’d get some unexpexted results because the state is asynchronous.
So whenever you use the previous state to update the state, you should use the callback function.

See a good explanation here (from minute 6:30):

1 Like