Middle
Why do we use functional state updates (passing a function to setState with the argument prev) instead of just count + 1?
sobes.tech AI
Answer from AI
Functional state updates in React are used when the new state depends on the previous one. If you simply write setCount(count + 1), then with multiple rapid calls, the state may be outdated due to asynchronous updates and batching.
Passing a function to setState guarantees that you receive the current value of the previous state prev, and based on it, you can correctly compute the new state:
setCount(prevCount => prevCount + 1);
This is especially important in situations with multiple consecutive updates, such as within event handlers or asynchronous functions.