Sub topic 11
Several updates in flight at once
A user can submit a second message before the first one reaches the server. This chapter covers what useOptimistic does when several optimistic updates overlap, and how to write code that stays correct in that case.
This chapter assumes you know:
useStateand lifting state upasync/await- Form actions and
startTransition - The two-argument form of
useOptimistic(state, updateFn), covered in earlier chapters
Why overlap happens
Sending a message takes a network round trip, often hundreds of milliseconds. Users type and press Enter faster than that. A like button can be tapped three times in a second. Each press starts a new Action while earlier Actions are still awaiting the server.
Each overlapping Action calls the optimistic setter. You need to know three things:
- How React combines several optimistic updates into one value.
- What happens when the real state changes while some updates are still pending.
- What your own code must do to avoid duplicates, unstable keys, and confusing errors.
How React combines pending updates
useOptimistic is not a second copy of your state that you mutate. React computes the optimistic value from two inputs:
- The base state, which is the first argument you pass to the hook, usually a prop or state from a parent.
- A queue of pending optimistic updates, each one the value you passed to the setter.
When you render, React starts at the base state and runs your update function once per queued update, in the order they were made. Each call receives the result of the previous call as currentState. The final result is optimisticState.
With three messages pending, the update function runs three times:
base = [m1, m2]
step 1: update(base, m3) -> [m1, m2, m3*]
step 2: update(step 1, m4) -> [m1, m2, m3*, m4*]
step 3: update(step 2, m5) -> [m1, m2, m3*, m4*, m5*](* marks optimistic items.) This is why an update function that appends to currentState works with several submissions. You never read the optimistic state yourself and add to it. React chains the calls for you.
Replay when the base state changes
The queue is not applied once and thrown away. If the base state changes while updates are pending, React starts again from the new base and re-runs the queued updates. Suppose the server confirms m3 and the parent updates messages to [m1, m2, m3] while m4 and m5 are still pending. The next render computes:
base = [m1, m2, m3]
update(base, m4) -> [m1, m2, m3, m4*]
update(.., m5) -> [m1, m2, m3, m4*, m5*]This replay behavior has two consequences for your code. The update function must be pure, because it can run many times for the same update. It must also be safe when the real state already contains something equivalent to a pending update.
The timeline of two overlapping sends
The diagram shows the common outcome, but timing details matter. React 19 runs overlapping async Actions as a group of related transitions. The optimistic layer reverts, and the new real state is shown, when the Actions that are pending have finished. In practice you may see the real list update once for several messages, or update message by message. Do not write code that depends on either. Write code that produces the right list in both cases.
A complete example
The next example is a runnable Thread that handles overlapping sends. It makes three choices on purpose, and the sections after it explain each.
import { useOptimistic, useState } from "react";
// Fake server: takes 1.5 s, rejects any text containing "fail".
function fakeServerSend(message) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (message.text.includes("fail")) {
reject(new Error("Rejected by server"));
} else {
resolve({ id: message.id, text: message.text });
}
}, 1500);
});
}
export default function App() {
const [messages, setMessages] = useState([]);
async function sendMessage(message) {
const saved = await fakeServerSend(message);
setMessages((current) => [...current, saved]);
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}
function Thread({ messages, sendMessage }) {
const [failures, setFailures] = useState([]);
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, message) => {
if (currentMessages.some((m) => m.id === message.id)) {
return currentMessages;
}
return [...currentMessages, { ...message, sending: true }];
}
);
async function formAction(formData) {
const text = String(formData.get("message") ?? "").trim();
if (!text) return;
const message = { id: crypto.randomUUID(), text };
addOptimisticMessage(message);
try {
await sendMessage(message);
} catch {
setFailures((current) => [...current, text]);
}
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>
{m.text}
{m.sending && <small> (Sending...)</small>}
</li>
))}
</ul>
{failures.map((text, i) => (
<p role="alert" key={i}>
Could not send: "{text}"
</p>
))}
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}Try it: send "one", then "two" within a second and a half. Both show "(Sending...)". Send "fail me" and the message appears, then vanishes, and an alert names the text that failed. The messages sent around it are unaffected.
Choice 1: create the ID outside the update function
The ID comes from crypto.randomUUID() in formAction, not inside the update function. The update function is replayed, so a random ID created inside it would be different on every replay. React would see a new key on each re-render, and the item would be unmounted and remounted. You would see flicker, lost focus, and restarted animations.
Treat the update function like a reducer. It must return the same output for the same inputs. Generate anything random or time-based (IDs, timestamps) in the Action and pass it in as the update value.
Choice 2: guard against the same item appearing twice
Replay can produce a state where the real list already contains the confirmed message while the queue still holds the update for it. Without a guard, the list would show the message twice for a moment. The check currentMessages.some((m) => m.id === message.id) turns the update into a no-op when the real state already has that ID.
For the guard to work, the server must return the same ID the client sent, as fakeServerSend does. If your server assigns its own IDs, you cannot match by ID. In that case match on something you do control, such as a client-generated clientId field that the server stores and echoes back.
Choice 3: track failures per item
A single error string, as in the earlier chapter, is fine for one request. With several in flight, a second failure would overwrite the first, and the user would lose information. Here failures is a list, and each entry names the text that failed. Production code often goes further and stores the failed message so the user can retry it.
Updates that replace instead of append
Not every optimistic update appends. A like button, a toggle, or a "mark as read" flag sets a value. With the single-argument form useOptimistic(liked), the setter replaces the optimistic value. The most recent call wins.
import { startTransition, useOptimistic } from "react";
function LikeButton({ liked, saveLiked }) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
function handleClick() {
startTransition(async () => {
setOptimisticLiked(!optimisticLiked);
await saveLiked(!optimisticLiked);
});
}
return (
<button onClick={handleClick}>
{optimisticLiked ? "Unlike" : "Like"}
</button>
);
}This version computes the next value from optimisticLiked, not from liked. If the user clicks twice quickly, the second click sees the optimistic result of the first and toggles back. If you wrote !liked instead, as the earlier example does for a single click, both clicks would send the same value. A button that looks toggled twice would then save "liked" twice.
Both variants have limits. The component reads optimisticLiked from the render in which the click happened. If two clicks fall in the same render, they both read the same value. When a toggle needs strict correctness under rapid input, either disable the control while the Action is pending (see the next section) or send the intended final value and let the server be idempotent, so repeating the same request is harmless.
Order and ordering guarantees
React replays optimistic updates in the order you made them. It does not guarantee that your network requests finish in that order. Request B can return before request A. Two things follow from this:
- The optimistic list always shows messages in submission order, because the queue is ordered. This is usually what you want.
- The real list is built by whatever your parent does when each request resolves. If the parent appends on completion, a slow A could end up after B in the real list, and the list would reorder when the optimistic layer disappears.
Pick one place to define order. Options include sorting the real list by a timestamp or sequence number from the server, serializing requests in the parent so B waits for A, or inserting the saved item at an index known before sending. Whichever you choose, the optimistic update function and the parent's real-state update must agree. If they do not, the user sees items jump when the optimistic layer ends.
Failure while others are still pending
When one request fails, React does not remove that single item from the queue. The optimistic layer ends when the Actions that are pending finish, and the list is recomputed from the real state. The failed message never reached the real state, so it disappears. Messages that succeeded are in the real state and stay.
If another Action is still pending when one fails, its optimistic item can remain visible, replayed on top of the current real state. That is the correct outcome. It is also the reason failure feedback must be tied to a specific item, as failures is above, and not a general "something went wrong".
Two limits to remember:
- React reverts the display for you but does not retry anything. Retry logic and user messaging are your job.
- If your Action catches the error and does not rethrow, React treats the Action as having succeeded. The revert still happens because the real state never changed, but error boundaries will not see the error. Rethrow only if you want an error boundary to handle it.
Preventing overlap on purpose
Sometimes the right design is to disallow overlap. Deleting a record, submitting a payment, and updating a shared counter are examples. Use useFormStatus in a child of the form to disable the button while an Action is pending, or keep your own isPending flag. Disabling input removes the overlap, so none of the replay concerns apply.
| Situation | Better approach |
|---|---|
| Chat messages, comments, list additions | Allow overlap; use client IDs and a deduplicating update function |
| Toggles and likes | Allow overlap if the server is idempotent; otherwise disable while pending |
| Payments, destructive deletes | Disable while pending; avoid optimistic display |
| Edits to the same field | Serialize requests, or send the latest value only |
Checklist for overlapping updates
- Generate IDs, timestamps, and any random value outside the update function.
- Make the update function pure and safe to run again on a new base state.
- Skip the update when the real state already contains the item.
- Define one ordering rule shared by the optimistic and real lists.
- Report failures per item, in a list or per-item state.
- Disable the control if overlap would be wrong, not just inconvenient.
Exercise
A teammate writes the update function as (current, text) => [...current, { id: crypto.randomUUID(), text, sending: true }] and notices that pending messages flicker and lose focus in an editable field when a second message is sent. What causes it, and how do you fix it?
Show answer
React replays the queued optimistic updates from the new base state whenever the real state changes or another update is added. Each replay runs the update function again, so crypto.randomUUID() produces a new ID for the same pending message. The list key changes, and React unmounts and remounts the item. The fix is to create the ID once in the Action (const message = { id: crypto.randomUUID(), text }), pass the whole message to addOptimisticMessage, and have the update function only add { ...message, sending: true }. The update function then returns the same result every time it runs.
Exercise
Two messages A and B are sent in quick succession. The server returns the saved A with the same id the client sent, and the parent appends it to messages while B is still pending. Why does the example's update function check currentMessages.some((m) => m.id === message.id), and what would you see without the check?
Show answer
When the real state changes, React replays the pending updates on top of the new base. If the queue still holds the update for A at the time the base already contains saved A, the unguarded function would add A again and the list would show A twice until the optimistic layer ended. The check makes the update a no-op when an item with the same ID is already in the real state. It only works if the server echoes the client-generated ID.