Sub topic 9
Handling Failures and Showing the Rollback
An optimistic update shows a result before the server confirms it. Sometimes the server says no. This chapter covers what React does when the request fails, why the user can miss the failure, and how to make the rollback visible.
This chapter assumes you can write function components with useState, use async/await with try/catch, and have read the earlier chapters on Actions, transitions and the useOptimistic signature. You should know that useOptimistic(state, updateFn) returns an optimistic value and a setter, and that the setter is called inside an Action.
What a failure looks like to the user
Suppose a user sends a chat message. The optimistic list shows it immediately. One second later the request fails. Without any error handling, the user sees this:
- The message appears in the list.
- The message vanishes.
- Nothing explains why.
The user may think the app is broken, or may assume the message was delivered. Both are wrong. Rolling back the UI is only half of failure handling. The other half is telling the user what happened and, where possible, letting them retry without retyping.
Why the rollback happens on its own
useOptimistic does not store the optimistic value permanently. It treats it as a temporary layer on top of the real state you pass in as the first argument. React applies that layer only while the Action that called the setter is still pending. When the Action finishes, React renders again using only the real state.
This has a consequence for failures. You do not write rollback code. You never call a "remove the optimistic message" function. If the request fails and you do not change the real messages state, the real list has no new message. When the Action ends, the optimistic layer is dropped, and the list shows the real state without the message.
The same mechanism handles success. If the request succeeds, you update the real state inside the Action. When the Action ends, the real list now contains the saved message, and the optimistic copy is dropped. Both outcomes use the same code path. The only difference is whether the real state changed.
A failure-aware message thread
The following component catches the error, stores a message for the user, and lets the rollback happen by leaving the real messages prop unchanged.
import { useOptimistic, useState } from "react";
function Thread({ messages, sendMessage }) {
const [error, setError] = useState(null);
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, text) => [
...currentMessages,
{ id: crypto.randomUUID(), text, sending: true },
]
);
async function formAction(formData) {
const text = formData.get("message");
setError(null);
addOptimisticMessage(text);
try {
await sendMessage(text);
} catch {
setError("Could not send your message. Please try again.");
}
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>{m.text}</li>
))}
</ul>
{error && <p role="alert">{error}</p>}
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}Four details matter here.
setError(null)runs first. It clears the error from a previous attempt, so a stale error does not sit next to a new pending message.addOptimisticMessageruns before theawait. The setter must be called while the Action is pending. Calling it before the firstawaitis always safe.- The
catchswallows the error. The Action then completes normally, which ends the optimistic layer. The error message is handled by your own state instead. - The error uses
role="alert". Screen readers announce the text when it appears, so users who cannot see the message disappear still learn that the send failed.
A runnable parent
The Thread component needs a parent that owns the real list. The parent below fakes a server call that fails when the text contains the word "fail", so you can try both outcomes.
import { startTransition, useState } from "react";
function fakeServer(text) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (text.toLowerCase().includes("fail")) {
reject(new Error("Network error"));
} else {
resolve({ id: crypto.randomUUID(), text });
}
}, 1000);
});
}
export default function App() {
const [messages, setMessages] = useState([]);
async function sendMessage(text) {
const saved = await fakeServer(text);
startTransition(() => {
setMessages((current) => [...current, saved]);
});
}
return <Thread messages={messages} sendMessage={sendMessage} />;
}sendMessage does not catch errors. When fakeServer rejects, the rejection travels up to the try/catch in Thread. This split is a good default: the parent owns the data and reports failure by throwing, and the component that owns the UI decides how to show it.
The startTransition call around setMessages matters. React tracks state updates inside an Action only until the first await. An update after an await is no longer marked as part of the transition unless you wrap it again. Wrapping keeps the real-state update in the same transition as the Action, so the swap from optimistic to real list happens in one render.
Type hello and the message shows at once and stays after one second. Type this will fail and the message appears, then disappears after one second, and the alert text appears.
What counts as "the Action ends"
The rollback timing depends on when the Action's promise settles. Three cases are worth separating.
| Case | What happens to the optimistic value | What the user sees |
|---|---|---|
| Request succeeds, real state updated | Dropped when the Action ends; the real state already holds the item | The item stays, without the pending marker |
| Request fails, error caught, real state unchanged | Dropped when the Action ends | The item disappears, plus your error text |
| Request fails, error not caught | Dropped when the Action ends; the error is reported to the nearest error boundary | The item disappears, and the error boundary's fallback renders |
The third case is easy to miss. In React 19, an error thrown out of an Action is rethrown during rendering, so an error boundary above the component will catch it. If there is no error boundary, the whole tree can unmount. Catch errors that you expect, such as network failures and validation rejections. Leave unexpected errors uncaught only if you have an error boundary that handles them.
Keeping what the user typed
There is a second problem in the thread above. When a form Action finishes, React resets uncontrolled form fields. After a failure, the input is empty, the message has vanished, and the user must retype it.
The fix is to remember the failed text and use it as the input's defaultValue. The reset then restores that value instead of clearing the field.
import { useOptimistic, useState } from "react";
function Thread({ messages, sendMessage }) {
const [error, setError] = useState(null);
const [failedText, setFailedText] = useState("");
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(currentMessages, text) => [
...currentMessages,
{ id: crypto.randomUUID(), text, sending: true },
]
);
async function formAction(formData) {
const text = formData.get("message");
setError(null);
setFailedText("");
addOptimisticMessage(text);
try {
await sendMessage(text);
} catch {
setFailedText(text);
setError("Could not send your message. Your text is still in the box.");
}
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>{m.text}</li>
))}
</ul>
{error && <p role="alert">{error}</p>}
<form action={formAction}>
<input type="text" name="message" defaultValue={failedText} />
<button type="submit">Send</button>
</form>
</>
);
}Now a failed send leaves the text in the input, and pressing Send again is a retry. The error message tells the user this. Clearing failedText at the start of each attempt keeps a successful send from leaving old text behind.
Choosing how loudly to fail
Not every failure needs the same treatment. Match the feedback to the cost of the lost work.
- Cheap, repeatable actions such as a like button: roll back silently or with a brief toast. The user can click again.
- User-authored content such as a message or a comment: show an error and keep the draft, as above.
- Actions with side effects the user must know about: show a persistent error, and consider not using an optimistic update at all (see the end of this chapter).
For the like button from the earlier chapter, the rollback alone is a clear signal. The button flips back to its previous label. If you also want a message, add an error state in the same way as in the thread.
Common mistakes
- Writing manual rollback code. Do not set the real state back to an older value or filter out the optimistic item yourself. The optimistic layer disappears on its own, and extra rollback code can remove real items.
- Putting the error only in the optimistic state. Error text that lives in the optimistic value vanishes with the rollback. Keep errors in ordinary
useState. - Updating real state before the request settles. If you add the item to
messagesfirst and then send, a failure leaves a fake item in the real list. Update real state only after the server confirms. - Calling the setter outside an Action. If you call the optimistic setter in a plain event handler, React warns that an optimistic update happened outside a transition, and the value may not behave as expected. Use a form action or
startTransition. - Forgetting that the error appears at a different moment than the rollback. Both happen around the end of the Action, but they are separate updates. Do not write code that depends on them landing in a specific order.
When failure handling tells you not to be optimistic
If a failure is common, expensive, or hard to explain, the rollback itself becomes the problem. A payment that appears to succeed and then reverses is worse than a spinner. Reasonable signals that an optimistic update is a poor fit:
- The server often rejects the request for reasons the client cannot predict.
- The result depends on server-computed values that you would have to guess.
- A reversal would confuse the user or cause real-world harm.
In these cases, show a pending state and wait for the server. A later chapter covers this decision in more detail.
Exercise
A user submits a comment. The optimistic comment appears, the request fails, and the code catches the error and calls setError. The code does not touch the real comments state. Why does the optimistic comment disappear, and what would be a bug in this design?
Show answer
The optimistic value only lasts while the Action is pending. When the Action ends, React renders from the real comments state, which never received the comment, so the comment disappears. A bug would be adding the comment to the real state before the request succeeds, or writing code that manually removes the optimistic item. The first leaves a fake comment in the real list after a failure. The second duplicates what React already does and can remove real items.
Exercise
After a failed send, the message box is empty and the user must retype. What causes this, and how do you fix it in the thread component?
Show answer
When a form Action finishes, React resets uncontrolled fields, even if the request failed and the error was caught. To fix it, store the failed text in state (for example failedText) in the catch block, and pass it to the input as defaultValue. Clear it at the start of the next attempt so a successful send does not bring old text back.
Exercise
Your Action calls addOptimisticMessage, awaits sendMessage, and then calls setMessages with the saved message, all in a form action. Why might wrapping the setMessages call in startTransition help?
Show answer
React keeps state updates inside an Action in the transition only until the first await. An update after the await is not marked as part of the transition. Wrapping it in startTransition puts it back in the same transition, so the real list updates together with the end of the optimistic layer and the user sees one clean swap.