React 19's useOptimistic Is a Trap If You Don't Model Failure First
useOptimistic feels like free UX magic until a server action fails in ways you didn't plan for. Here's the mental model we wish we'd had before shipping it to production.
useOptimistic ships with a demo that fits on a slide: type a message, it appears instantly, the server catches up. Everything about the API suggests it's a drop-in UX win. In practice, it's the hook we've rewritten the most times across client projects in the last year — not because it's buggy, but because teams reach for it before they've modeled what failure actually looks like in their UI.
This is the write-up we wish we'd had before the first time we shipped it on a real form.
What useOptimistic actually gives you
Strip away the marketing and the hook does one thing: it lets you render a projected state during a transition, then snaps back to the real state when the transition finishes. That's it. It does not retry. It does not queue. It does not know about errors. It does not persist across navigations.
The signature is deceptively small:
const [optimisticState, addOptimistic] = useOptimistic<State, Action>(
realState,
(current, action) => reducer(current, action)
);
The mental model most teams start with is "optimistic update = temporary write." That's wrong, and it's the source of every bug we're about to describe. The correct model is: optimisticState is a pure function of realState plus any in-flight actions inside the current transition. The moment the transition ends — success or failure — the projection evaporates and you are back to whatever the server told you.
If you internalise that, the rest of this article is obvious. If you don't, you will ship ghost rows.
The three failure modes nobody designs for
We've audited enough App Router codebases to see the same three bugs on repeat.
1. The silent snapback
A user clicks "Mark as paid." The row updates instantly. The server action throws because the invoice was already settled by another teammate. The row flips back to "unpaid" with no explanation, and the user clicks it again. And again.
The optimistic projection disappeared when the transition ended, but nothing told the user why. There's no error boundary involved because the server action returned a result object, not a thrown exception — which is the pattern most form libraries now recommend.
2. The ghost row
A user adds a comment. It appears. The server action fails due to a validation error. The optimistic comment vanishes, but the textarea has already been cleared by the form's action prop. The user's text is gone, the comment is gone, and they have no idea anything went wrong.
3. The racing transition
A user toggles a switch three times in a second. Each toggle is its own startTransition. React batches them, but the server actions resolve out of order. The final rendered state matches neither the user's last click nor the server's truth, because the reducer was applied against stale realState snapshots.
All three bugs share a cause: the team modeled the happy path as the whole path.
A failure-first pattern
Here's the shape we now reach for by default. It's not clever. It's just honest about the fact that server actions return results, not promises of success.
'use client';
import { useOptimistic, useTransition } from 'react';
import { toast } from '@/components/toast';
type Invoice = { id: string; status: 'paid' | 'unpaid' };
type OptimisticAction =
| { type: 'mark-paid'; id: string }
| { type: 'revert'; id: string; previous: Invoice['status'] };
export function InvoiceRow({
invoice,
markPaidAction,
}: {
invoice: Invoice;
markPaidAction: (id: string) => Promise<
{ ok: true } | { ok: false; reason: string }
>;
}) {
const [isPending, startTransition] = useTransition();
const [optimistic, applyOptimistic] = useOptimistic(
invoice,
(current, action: OptimisticAction) => {
if (action.type === 'mark-paid' && action.id === current.id) {
return { ...current, status: 'paid' };
}
return current;
}
);
function onClick() {
startTransition(async () => {
applyOptimistic({ type: 'mark-paid', id: invoice.id });
const result = await markPaidAction(invoice.id);
if (!result.ok) {
toast.error(`Could not mark paid: ${result.reason}`);
}
});
}
return (
<button
onClick={onClick}
disabled={isPending || optimistic.status === 'paid'}
aria-busy={isPending}
>
{optimistic.status === 'paid' ? 'Paid' : 'Mark as paid'}
</button>
);
}
Four things to notice:
- The server action returns a discriminated result, never throws for business errors. This is the only way to communicate why a failure happened without losing the user's context.
- The toast fires inside the transition, so the user sees the error at the same instant the row snaps back. There is no "silent snapback."
aria-busygives assistive tech a hook. If you skip this, you will fail your next accessibility audit.- The button is disabled while pending, which kills the racing transition problem for single-row toggles.
That last point deserves its own section.
Lists are harder than rows
Single-row toggles are easy. Lists — adding, removing, reordering — are where useOptimistic earns its complexity budget.
The pattern we use: project the list as real + pending, and tag every pending item with a client-generated id so you can reconcile when the server responds.
type PendingComment = {
clientId: string;
body: string;
status: 'sending' | 'failed';
};
type Action =
| { type: 'add'; comment: PendingComment }
| { type: 'fail'; clientId: string };
const [optimistic, dispatch] = useOptimistic(
{ real: comments, pending: [] as PendingComment[] },
(state, action: Action) => {
if (action.type === 'add') {
return { ...state, pending: [...state.pending, action.comment] };
}
if (action.type === 'fail') {
return {
...state,
pending: state.pending.map((p) =>
p.clientId === action.clientId ? { ...p, status: 'failed' } : p
),
};
}
return state;
}
);
Now when a submission fails, the item stays visible with a failed status — the user can retry inline instead of re-typing. When it succeeds, the server's revalidated comments list replaces the projection and the pending item quietly disappears because it's no longer in-flight.
The failed-state projection only works because the transition is still running when you dispatch fail. Once the transition closes, that pending array is gone. In our experience this catches most teams off guard the first time: you need to keep the transition open (don't await outside it) or escalate the failure into real state via useState for anything you want to survive.
When not to use useOptimistic at all
We've started telling clients to skip it entirely for three categories:
- Financial writes where the user needs certainty the write happened. Showing "transferred" and then snapping back is worse than a 400ms spinner.
- Multi-step flows where the next screen depends on the server's generated id. You cannot optimistically route.
- Low-frequency actions where the perceived latency is already under 200ms. The hook has a cost in cognitive complexity and bundle size; spend it where it matters.
useOptimistic is a UX tool for high-frequency, low-stakes, fast-feedback interactions. Likes, toggles, list additions, inline edits. That's the sweet spot.
The accessibility bit people skip
Optimistic UI is an accessibility problem disguised as a UX win. Sighted users see the state flip. Screen reader users get nothing unless you tell them.
Minimum viable approach:
aria-busyon the control that initiated the action.- An
aria-live="polite"region near the affected content for success,aria-live="assertive"for errors. - Don't move focus on optimistic success. Move it only when the real state confirms, otherwise you'll yank focus back on failure.
If your design system doesn't have a status region primitive yet, that's the first thing to build before you roll useOptimistic out across an app. We've written more on this approach in our design systems work.
Where we'd start
If you're about to add useOptimistic to a feature next week, do these four things in order before you write the hook:
- Rewrite the server action to return a
{ ok: true } | { ok: false; reason }result. No thrown business errors. - Sketch the failure UI on paper. Where does the error appear? Does the user lose input? What do they click next?
- Add an
aria-liveregion to the component now, even if it's empty. You'll need it. - Only then reach for
useOptimistic, and keep the reducer pure — no fetches, no side effects, noDate.now().
The hook is good. It's just not the feature. The feature is your failure story. Build that first, and the optimistic part is the easy fifteen minutes at the end.
Want a team like ours?
72Technologies builds production software for the kind of teams who actually read this blog.
Start a projectKeep reading
Streaming Suspense Boundaries: Where We Put Them Wrong for Two Years
We treated Suspense as a loading-state tool. It's actually a streaming contract with the browser, and putting boundaries in the wrong place costs you LCP, CLS, and sometimes the whole page.
The `use cache` Directive Looked Clean Until We Shipped It
Next.js's `use cache` directive promised a cleaner caching model than fetch options and tags. Six weeks into production, we found three failure modes that aren't in the docs — and one that cost us a weekend.
Partial Prerendering in Production: What Broke, What Held
We shipped Next.js Partial Prerendering to a high-traffic marketing-plus-dashboard app. Here's what actually worked, what silently regressed, and the debugging patterns we wish we'd had on day one.
