Guaranteeing Sequential Updates
What you'll learn: How functional updates ensure that multiple setState calls in quick succession all apply correctly, even before re-render.
The Problem: Sequential Calls, Single Snapshot
When you call setState multiple times rapidly—say, within the same event handler—all those calls operate on the same snapshot of state. React batches the updates together and only re-renders once, but if you're using direct updates like setValue(value + 1), each call reads the same stale value.
This means three calls to setValue(value + 1) might only increment by 1, not 3, because all three calls see the same old value.
The Solution: Functional Updates
The functional update syntax—setState(prev => ...)—solves this by guaranteeing sequential application. Each update receives the result of the previous update as its argument, even if they all happen before the re-render.
setValue(prev => prev + 1); // prev = 0, returns 1
setValue(prev => prev + 1); // prev = 1, returns 2
setValue(prev => prev + 1); // prev = 2, returns 3
React queues these updates and applies them in order, passing the output of one as the input to the next. You're guaranteed that the final state reflects all three increments.
When This Matters Most
This pattern is critical when:
- Multiple updates happen in rapid succession (user clicking fast, multiple async callbacks)
- Updates depend on the previous state
- You can't predict the order or timing of setState calls
Key Takeaway: Functional updates (setState(prev => ...)) guarantee that multiple sequential updates all apply correctly by passing the previous update's result to the next, eliminating race conditions caused by stale state snapshots.