setState with function argument in React

One of the articles on correct way of using setState says that when the new state depends on old state, it is better to use function form of setState i.e. this.setState((prevState)=>{}). I az not able to find any situation where this.setState({}) would cause issues. Does anyone have an example for it ?

Sure here is an example.

It can cause an issue when the new state depends on the old state, or more specifically, when the order/timing of the setStates matter.

For example, imagine that you had a video game where they get 100 points for every baddie they shoot, but if they shoot the super-baddie, it doubles their points. There the order matters. Let’s say they start out with 1000 points.

start                 points = 1000
shoot baddie          points = 1100
shoot baddie          points = 1200
shoot super-baddie    points = 2400

But with the objective setState, you are not guaranteed order. So, even though the sequence of events was what we see above, what redux will see is below:

start                 points = 1000
shoot baddie          points = 1100
shoot super-baddie    points = 2200
shoot baddie          points = 2300

So, the order is important because the calculation is based on the previous points value. The function setState guarantees the order. There is also the possibility with the objective setState that repeated calls come in with the same value, it may batch/combine them together and get odd results, removing repeated calls with the same object, the last one overwriting the earlier ones.

So, if you are setting state to a simple value, the old way is probably fine. If you are basing it on previous state, especially if there is a chance of them coming in rapid succession, then the “new” functional way is better.

Here is React’s explanation. Part of being a developer is being good at finding and reading docs.