Sub topic 12
When an optimistic update is the wrong choice
This chapter assumes you can build the optimistic message list from earlier chapters. You should know how useOptimistic derives a temporary value from real state. You should also know that React discards that value when the Action finishes, and how to show an error after a failed request. Here you will learn to recognize cases where the pattern does more harm than good, and what to use instead.
What an optimistic update costs
An optimistic update spends accuracy to buy speed. The UI shows a result before the server has agreed to it. That is a good trade when the guess is almost always right and a wrong guess is cheap to undo.
The trade goes bad when either condition fails. A wrong guess can be common, and a wrong guess can also have a high cost. The costs fall into four groups:
- Trust. The user sees "Done" and acts on it, then the screen changes back.
- Side effects. The server may have done something that cannot be undone, or the UI may have implied something that never happened.
- Complexity. Each optimistic path needs a pending style, an error path, and a key strategy.
- Misleading data. The UI may show values the client cannot compute correctly.
Because useOptimistic reverts automatically, rollback is easy to implement. It does not make rollback safe for the user. React restores the real state, but it does not tell anyone that their action failed.
A decision flow
Ask these questions in order for any candidate interaction. Stop at the first "no".
The sections below explain each question.
The client cannot predict the result
useOptimistic only works when your update function can produce the next state from the current state and the input. If the server decides part of the result, your guess will be wrong in some visible way.
Common server-owned values:
- Totals with tax, shipping, discounts, or currency conversion.
- Rankings, balances, and counters that other users also change.
- Generated IDs, timestamps, and slugs that appear in links.
- Search results, recommendations, and anything produced by a query.
A temporary ID is acceptable in a message list because the user never sees it. A made-up order total is different, because the user reads it. If you show $41.00 and the server later says $44.35, the user has been misled for a moment, and in a checkout that may count as a defect.
A workable compromise is to show only the part you know. Optimistically add the line item and leave the total in a pending style until the server answers. If you cannot split the state that way, do not use the pattern.
The action is not reversible
React can discard a local value, but it cannot undo what the server did. Three situations make this matter.
Irreversible operations. Payments, account deletion, sending an email, publishing a post, and transferring money all fall here. Showing "Payment complete" before the charge is confirmed is wrong even if the revert is clean. The user may close the tab, which makes the optimistic state their only memory of the event.
Operations with partial success. The server may write the record, then fail to send the notification, then return an error. The client rolls back, so the item disappears. The server still has the record. The user retries and creates a duplicate. Idempotency keys on the server reduce this risk, but they are a server feature, not something useOptimistic provides.
Operations the user cannot cancel. After an optimistic "Message sent", the user may reasonably expect a way to take it back. If the interface has no such control, the false confirmation does harm.
If an action fails halfway, the optimistic state has already shown a success screen. Showing that screen for a destructive action is worse than showing a spinner for a moment longer.
Failure is common or must be explained
The automatic revert is silent by design. When the Action ends, React shows the real state again. If the request failed, the item vanishes and the user must work out why. The error-handling chapter covered adding a message. That covers the mechanics, but for some features the failure rate makes the whole approach poor.
Treat these as warning signs:
- The server often rejects the input, as with username availability, coupon codes, and form validation that only the server can do.
- The action depends on permissions that may have changed since the page loaded.
- The network is unreliable for your users, such as mobile clients with weak signal.
- The user must fix something and resubmit. In that case the optimistic item made them believe their input was accepted.
For validation, run what you can on the client before the Action starts. Then only server-only checks remain, and you can wait for those instead of guessing.
A common error is to treat the silent revert as a feature. It is only a feature when the user does not need to know. Hiding a failed "like" is fine. Hiding a failed "submit expense report" is not.
The wait is already short
Optimistic updates also add work for you. Each one needs a reducer function, a pending style, an error message, and a key plan. If the request finishes in 50 ms, none of this is visible to the user, and a plain useState or a normal transition is enough.
Measure before adding it. Look at the slowest realistic case, not the average. A request that takes 40 ms on your development machine may take two seconds on a phone.
The opposite mistake also exists. Do not add optimism to hide a slow server when the real fix is making the server faster. The pattern improves how the wait feels, not how long it is.
Concurrency and shared data
Several overlapping optimistic updates are manageable in a single-user list, because each Action adds its own item. They become hard when the data is shared or order matters.
Be cautious in these cases:
- Editing the same record twice. Two quick edits each produce an optimistic value, but the server may apply them in a different order, so the final real state can differ from the last thing the user saw.
- Collaborative data. Another user may change the same list while your Action is in flight. When your Action ends and real state returns, the list may jump.
- Dependent actions. If step two uses an ID created in step one, an optimistic step one has no real ID yet. Step two cannot run until step one finishes, so the optimism buys nothing.
- Ordering. If new items must go in a server-defined position, such as sorted by score, then your optimistic item will land in the wrong place and move later.
Layout shifts are a quiet cost. An item that appears at the bottom and later jumps to the top is more distracting than a spinner.
Alternatives to use instead
When you decide against an optimistic update, you still want to avoid a frozen screen. React gives you several tools that show progress without claiming success.
| Situation | Better choice |
|---|---|
| Result is server-computed | Pending state on the changed region, then show the real value |
| Irreversible action | Disable the control, show a spinner, confirm after the server responds |
| Form with server validation | Use `useFormStatus` or `useActionState` to show progress and errors |
| Fast request | Plain state or a transition, with no extra UI |
| Dependent steps | Run steps in order and show step progress |
Here is a checkout button that waits for the server. It uses useTransition, which gives you an isPending flag for the whole Action.
import { useState, useTransition } from "react";
export function PayButton({ placeOrder }) {
const [isPending, startTransition] = useTransition();
const [status, setStatus] = useState("idle");
function handleClick() {
setStatus("idle");
startTransition(async () => {
try {
await placeOrder();
setStatus("paid");
} catch {
setStatus("failed");
}
});
}
return (
<div>
<button onClick={handleClick} disabled={isPending}>
{isPending ? "Processing payment..." : "Pay now"}
</button>
{status === "paid" && <p>Payment confirmed.</p>}
{status === "failed" && (
<p role="alert">The payment did not go through. You were not charged.</p>
)}
</div>
);
}Nothing here claims success early. The message "Payment confirmed" appears only after placeOrder resolves. The button is disabled during the wait, which also prevents a double submit.
A middle path: limit what the optimistic item can do
Sometimes the action fits the pattern but the optimistic item can cause trouble if the user interacts with it. The usual fix is to mark it as pending and block actions that need a real ID.
import { useOptimistic } from "react";
export function Thread({ messages, sendMessage, deleteMessage }) {
const [optimisticMessages, addOptimisticMessage] = useOptimistic(
messages,
(current, text) => [
...current,
{ id: crypto.randomUUID(), text, sending: true },
]
);
async function formAction(formData) {
addOptimisticMessage(formData.get("message"));
await sendMessage(formData);
}
return (
<>
<ul>
{optimisticMessages.map((m) => (
<li key={m.id}>
{m.text}
<button
type="button"
disabled={m.sending}
onClick={() => deleteMessage(m.id)}
>
Delete
</button>
</li>
))}
</ul>
<form action={formAction}>
<input type="text" name="message" />
<button type="submit">Send</button>
</form>
</>
);
}The delete button is disabled while sending is true. Without that check, the user could call deleteMessage with a temporary ID that the server has never seen. That request would fail, or worse, delete the wrong thing.
If you find yourself adding many such guards, treat that as a signal. Each guard is a place where the optimistic state differs from reality, and the pattern may not fit.
Accessibility and trust
Optimistic updates change what assistive technology announces. A screen reader may announce a new list item that later disappears. Use a live region for status messages, and make the pending state available in text, not only through color or opacity.
For features where users rely on the result, such as financial or medical data, prefer honesty over speed. A short wait with a clear message builds more trust than a fast screen that sometimes lies.
Summary checklist
Use useOptimistic when all of these hold:
- Your code can compute the next state from known inputs.
- The action is reversible and has no side effects the user would care about.
- The server rejects it rarely, and you have an error message ready for when it does.
- The wait is long enough that a user would notice it.
- Overlapping updates and shared edits will not make the list jump or reorder.
If any item fails, show a pending state and update the screen after the server responds.
Exercise
A "Place order" button charges the user's card. A teammate proposes using useOptimistic to show "Order placed" immediately so the page feels fast. Give two reasons this is the wrong choice and say what to do instead.
Show answer
First, the charge is irreversible and has side effects. If the server later rejects the card, React reverts the local state, but the user has already seen a false confirmation and may have left the page. Second, the order number, total, and tax come from the server, so the client cannot predict what to show. Instead, use useTransition (or useActionState) to disable the button and show "Processing..." while the Action runs. Show "Order placed" only after the server responds successfully, and show a clear error if it fails.
Exercise
In the Thread example, why is the Delete button disabled when m.sending is true?
Show answer
An optimistic message has a temporary ID created by crypto.randomUUID(), which the server has never seen. Calling deleteMessage with that ID would fail or target the wrong record. Disabling the button until the real message replaces the optimistic one avoids sending requests that depend on an ID that does not exist on the server.