Sub topic 5
How the Optimistic Value Is Replaced by Real State
This chapter assumes you know useState, props, async/await, and the basic useOptimistic call from earlier chapters. It covers what happens after you call the optimistic setter: when React shows the optimistic value, when it discards it, and what you must do so that the swap to real state looks seamless.
The optimistic value is derived, not stored
useOptimistic does not keep a second copy of your data that you later clean up. It holds a list of pending optimistic updates and computes the value you see on every render:
optimisticState = pending updates applied, in order, on top of the state argumentThe first argument to useOptimistic is the base. It is normally a prop or a useState value that represents what the server has confirmed. The update function (the reducer form) is the rule for combining the base with each pending update.
So the hook has no "revert" step. When no Action is pending, the list of pending updates is empty, and the result is the base itself. The optimistic value goes away because React stops applying updates, not because it deletes anything.
The lifecycle of one Action
An optimistic update lives only as long as the Action (the transition) that called the setter. Calling addOptimisticMessage inside a form action or inside startTransition(async () => { ... }) ties the update to that Action.
The same sequence in a table:
| Phase | What `useOptimistic` returns | Why |
|---|---|---|
| Before the Action | The base state | No pending updates |
| After the setter call, Action still pending | Base with the optimistic update applied | The update is attached to a pending Action |
| After the server responds, Action still pending | Still the optimistic version | The Action has not finished |
| Action finishes | The base state as of that render | The pending updates are discarded |
The key rule is in the last row. React drops the optimistic update when the Action finishes. It does not check whether the request succeeded or whether the base now "contains" the same data.
Reverting is unconditional
The optimistic value is discarded in two cases that look different to the user:
- On success, the parent has committed the confirmed data to the base state, so the base now includes the new item. The user sees the optimistic item replaced by the real one.
- On failure, the base never changed, so the item disappears.
Both cases use the same mechanism. Your code only decides whether the base state changed before the Action ended.
This has a practical consequence: you must update the real state yourself, as part of the Action. If you never update the base, a successful request looks like a failed one, because the optimistic item vanishes and nothing replaces it.
A complete example that shows the swap
The following component pair is runnable. The fake server accepts any message that does not contain the word "fail". Try both.
import { startTransition, useOptimistic, useState } from "react";
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function fakeServer(text) {
await wait(1000);
if (text.toLowerCase().includes("fail")) {
throw new Error("Server rejected the message");
}
return { id: crypto.randomUUID(), text };
}
export default function App() {
const [messages, setMessages] = useState([{ id: "m1", text: "Hello" }]);
async function sendMessage(text) {
try {
const saved = await fakeServer(text);
// Update the real state before this function returns.
startTransition(() => {
setMessages((current) => [...current, saved]);
});
} catch (err) {
console.error(err.message);
}
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}
function Thread({ messages, sendMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, text) => [
...current,
{ id: `temp-${crypto.randomUUID()}`, text, sending: true },
]
);
async function formAction(formData) {
const text = formData.get("message");
addOptimisticMessage(text);
await sendMessage(text);
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id} style={{ opacity: m.sending ? 0.5 : 1 }}>
{m.text}
</li>
))}
</ul>
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}Walk through a successful send of "Hi":
addOptimisticMessage("Hi")makesoptimisticMessagescontain two items, "Hello" and a dimmed "Hi" with atemp-id.- For one second the server call is pending. The list does not change.
fakeServerresolves.setMessagesstores the confirmed message in the parent, inside astartTransition.formActionreturns, so the Action ends. React commits the newmessagesand drops the optimistic update in the same render. The list shows "Hello" and "Hi", now at full opacity and with the server's id.
Now send "fail". Steps 1 and 2 are the same. In step 3 the catch runs and setMessages is never called. When the Action ends, the base is still [Hello], so "fail" disappears. The user gets no explanation. The error handling chapter shows how to add one.
Why the real update goes inside `startTransition`
In React 19, state updates that run after an await inside an async Action are not automatically marked as part of the transition. Wrapping setMessages in startTransition keeps it with the Action. That way the new base and the end of the optimistic phase commit together, with no frame where the optimistic item is gone and the real one has not arrived. If the real state came from a Server Function or a framework cache, the framework usually performs this step for you.
What if the base changes while the Action is pending?
The base can change for reasons unrelated to your Action: a polling refresh, a WebSocket message, or another form. React handles this by re-applying the pending updates on top of the new base.
Suppose the base is [A], and the user adds optimistic "B". The server pushes message "C" while the request is pending. React renders:
- base
[A, C] - plus pending update B
- result
[A, C, B]
This re-application is why the update function must be a pure function of (currentState, value). React may call it more than once for the same update, and it must return the same result each time given the same inputs. Do not read mutable variables, call Math.random(), or write to external state inside it. The crypto.randomUUID() in the example is a mild exception, because a re-run produces a different id for the same item. This can cause a remount of that list row. If this matters to you, generate the id before calling the setter and pass it in as part of the value:
function formAction(formData) {
const tempId = `temp-${crypto.randomUUID()}`;
addOptimisticMessage({ id: tempId, text: formData.get("message") });
// ...
}The reducer then just does [...current, { ...value, sending: true }] and stays deterministic. The temporary IDs chapter covers keys in more depth.
Common errors
The setter is called outside an Action
If you call the optimistic setter from a plain event handler, React warns that an optimistic update occurred outside a transition or Action. The update also has no Action to belong to, so it does not behave as intended. Call it from a form action, or inside startTransition.
// Wrong: not in an Action
function handleClick() {
setOptimisticLiked(!liked);
saveLiked(!liked);
}
// Right
function handleClick() {
startTransition(async () => {
setOptimisticLiked(!liked);
await saveLiked(!liked);
});
}The Action ends before the real state is updated
If your Action function returns before the base state changes, the user sees the item disappear and then reappear when the data arrives. Typical causes:
- Not awaiting the request:
sendMessage(text)withoutawaitends the Action immediately. - Updating state in a
setTimeoutor an unrelated callback after the Action returned. - Relying on a refetch that completes after the Action. Await the refetch inside the Action instead.
Expecting the optimistic value to persist
Some developers expect the optimistic item to remain after an error, with a "retry" button. React will not keep it. If you want a failed item to stay visible, store it in real state (for example with a status: "failed" field) in your catch block, and let the base carry it.
Mutating the base in the reducer
Returning current.push(item) or modifying current in place corrupts the real state, because the optimistic reducer receives the base object itself. Always return a new array or object.
Using optimistic state as the source of truth
Do not pass optimisticMessages back into the Action's server call or into a setMessages update. It contains items the server has not confirmed. Compute server payloads from the real messages or from the submitted form data.
Summary of the rules
- The optimistic value is the base plus pending updates, computed during render.
- Pending updates last exactly as long as the Action that created them.
- When the Action ends, the base is shown, whether or not the request succeeded.
- Update the base inside the Action, before it returns, if you want the change to persist.
- The reducer is replayed when the base changes, so keep it pure.
Exercise
A developer's formAction calls addOptimisticMessage(text), then calls sendMessage(text) without await. sendMessage succeeds after one second and calls setMessages in the parent. What does the user see, and how do you fix it?
Show answer
The Action ends as soon as formAction returns, which is almost immediately because the promise is not awaited. React drops the optimistic message at that point, so the message flashes briefly and disappears. About one second later the real message appears when setMessages runs. Fix it by writing await sendMessage(text) so the Action stays pending until the request finishes and the real state is set before the Action ends.
Exercise
The base list is [A]. The user submits a message and the reducer appends optimistic item B. While the request is pending, a WebSocket handler sets the base to [A, C]. What does useOptimistic return during the remaining pending time, and why does the reducer need to be pure?
Show answer
It returns [A, C, B]. React re-applies the pending update B on top of the new base [A, C]. Because React can call the reducer again for the same pending update whenever the base changes, the reducer must return the same output for the same inputs and must not mutate current or depend on outside mutable state.
Exercise
A request fails, and the catch block does nothing. Which line of code makes the optimistic item disappear, and what would you change if you wanted a failed message to stay on screen with a "Failed" label?
Show answer
No line removes it. The item disappears because the Action ends and React stops applying the pending update, while the base never included the item. To keep it visible, add it to the real state in the catch block, for example setMessages((c) => [...c, { id: tempId, text, status: "failed" }]) inside startTransition, and render the "Failed" label from status.