Day 5 of Learning React: Batching and Functional Updates
I thought calling a state setter multiple times caused multiple renders.
I was wrong.
React is smarter than that. It uses a process called Automatic Batching.
Instead of rendering after every single update, React groups them together. It collects all updates and performs one single render. This saves performance.
Here is what I learned today.
The Batching Process When you call multiple state functions, React follows this flow:
- Multiple state updates occur.
- React batches them together.
- React performs one render.
- React commits the changes to the UI.
The Problem with Standard Updates I tried this code: setCount(count + 1); setCount(count + 1); setCount(count + 1);
I expected the count to go from 0 to 3. It went from 0 to 1.
This happens because setCount(count + 1) does not mean "increase the count." It means "set the count to this specific value."
If count is 0, every line tells React to set the count to 1. React batches these and sees the final instruction is to set the count to 1.
The Solution: Functional Updates To fix this, you must use a functional update. This uses the latest state available in the update queue.
The correct way: setCount((prev) => prev + 1);
When you use this pattern, React gives each update the most recent value.
- First update: 0 + 1 = 1
- Second update: 1 + 1 = 2
- Third update: 2 + 1 = 3
Now the counter actually reaches 3.
A Common Mistake I once wrote: setCount((prev) => { prev + 1 });
The counter became undefined. When you use curly braces in an arrow function, you must use the return keyword. Use this instead: setCount((prev) => prev + 1);
Key Takeaways:
- React batches multiple state updates to improve speed.
- setState calls do not always trigger immediate renders.
- Standard updates use the value from the current render cycle.
- Functional updates use the latest state from the update queue.
- React uses an internal Update Queue to manage these changes.
