Sub topic 11
Several updates in flight at once
This chapter assumes you know useOptimistic with an update function, and that the optimistic value reverts when the Action finishes. It covers what happens when the user triggers a second update before the first one has finished.
What React does with overlapping updates
Every call to the setter inside an Action adds an entry to a queue. React doesn't overwrite the previous optimistic value. It starts from the real state you passed in, then runs your update function once per queued entry, in order. Each call receives the result of the previous one.
This is why the update function is the right tool here. With the reducer form, three quick clicks produce three layered changes. With the replace form (no update function), the last value wins.
A counter that accumulates
A quantity stepper shows the pattern in a small example. Each click adds a delta, so fast clicks stack.
import { startTransition, useOptimistic } from "react";
function QuantityStepper({ quantity, changeQuantity }) {
const [optimisticQuantity, addOptimisticDelta] = useOptimistic(
quantity,
(current, delta) => current + delta
);
function handleClick(delta) {
startTransition(async () => {
addOptimisticDelta(delta);
await changeQuantity(delta);
});
}
return (
<div>
<button onClick={() => handleClick(-1)}>-</button>
<span>{optimisticQuantity}</span>
<button onClick={() => handleClick(1)}>+</button>
</div>
);
}Start with quantity at 2 and click + three times quickly. The display goes 3, 4, 5 immediately. Each changeQuantity(1) call is sent to the server. The parent updates quantity to its real value when the requests complete.
Why the reducer must be a pure function of its inputs
React may run your update function again whenever the base state changes. If the parent passes in a new quantity while an Action is still pending, React replays the queue on top of the new value. That only works if the function uses nothing but its two arguments.
- Don't read outside variables such as
quantityfrom the closure. They can be stale. Use thecurrentargument. - Don't mutate
current. Return a new array or object. - Don't generate side effects such as network calls or logging inside it.
A related trap is a toggle. This reducer is unsafe if two clicks overlap:
// Risky: each click flips whatever the previous layer produced
(current) => !currentTwo quick clicks flip the value twice and show the original state, even though the user meant "like" and then "like again". For a like button, prefer the replace form and pass an explicit target value, as the LikeButton example does. For counters and lists, use deltas and appends.
Lists with several pending items
For a message list, appending is naturally safe for several in-flight sends. Each pending message needs its own key, so give every one a unique temporary ID when you create it. The crypto.randomUUID() call in the update function from the earlier chapters does that. Be aware that React may call the update function more than once for the same entry when it replays the queue. A random ID generated inside the reducer would then change between runs, and React would remount that row. If you see list items flicker, create the ID in the event handler and pass it in:
async function formAction(formData) {
const text = formData.get("message");
addOptimisticMessage({ id: crypto.randomUUID(), text });
await sendMessage(text);
}The reducer then becomes (current, message) => [...current, { ...message, sending: true }], and the ID stays stable across replays.
How failures interact
If the first request fails and the second succeeds, the optimistic layers still disappear only when their Actions end. After that, the real state decides what is visible. A failed message is gone from the list because the server never confirmed it, and the successful one appears because the parent added it to messages. Keep error messages per request if users can send several things at once, since a single error string can be overwritten by the next submit.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Reading a closure variable in the reducer | Wrong value after rapid clicks | Use the `current` argument |
| Toggling in the reducer | State flips back when clicks overlap | Pass an explicit target value |
| Random ID created inside the reducer | Rows flicker or remount | Create the ID in the handler |
| One shared `error` string | Earlier failure message disappears | Store errors per item or per request |
Exercise
A user clicks the "+" button of the QuantityStepper twice quickly, starting from a real quantity of 4. What does the stepper show right after the second click, and why? What does it show after both requests finish and the parent passes quantity 6?
Show answer
It shows 6 right after the second click. React starts from the real value 4 and replays the queue: 4 + 1 = 5, then 5 + 1 = 6. After both Actions finish, the optimistic layers are discarded and the stepper shows the real prop, which is 6, so the display looks unchanged.