React Server Components 19 🧬 useOptimistic — Instant UI updates before server confirmation
useOptimistic is the hook that makes a mutation feel instantaneous even though the server has not confirmed it. It accepts the canonical state and returns a copy that can diverge while an async action is in flight. When the action settles, the optimistic copy is discarded and the UI reconciles with the real state. If the action fails, the divergence disappears and the user sees the truth. The hook does not make the server faster; it makes the wait invisible.
The React documentation describes it precisely: useOptimistic “lets you show a different state while an async action is underway” . The mechanism is a pure update function that merges the optimistic value into the current state. The hook returns the merged state and a dispatch function. The dispatch must be called inside a transition or an action, or React warns and the optimistic value reverts immediately . This constraint is not incidental—it is the boundary that tells React when the optimistic window opens and closes.
Key point: useOptimistic is a rendering illusion with a strict lifetime. The optimistic state exists only while a transition is pending. The moment the transition settles, the illusion ends—either because the server confirmed the change or because the action threw and React reverted to the canonical state. The hook does not manage errors, retries, or validation. It manages the gap between intent and confirmation.
Why useOptimistic exists
The perceived latency problem. A mutation that takes 400 milliseconds to confirm feels instant on a fast connection and broken on a slow one. The user clicks “Like,” nothing happens, they click again, and the request doubles. useOptimistic closes that gap by rendering the expected outcome before the request completes. The React documentation’s example is a message that appears in the list with a “Sending…” label the moment the user submits, before the server has received it . The perception of speed is the feature.
The manual rollback problem. Before React 19, optimistic UI required snapshotting the current state, applying the optimistic change, awaiting the request, and reverting to the snapshot on failure. This pattern appeared in every optimistic interaction, duplicated with subtle variations, and each duplication introduced the possibility of a missed revert or a stale snapshot. useOptimistic collapses the snapshot-and-rollback logic into a single hook that reverts automatically when the action settles . The developer writes the merge function; React handles the lifecycle.
The transition boundary. The hook is designed to work inside startTransition or an action prop. The React documentation states that calling the dispatch function inside an action prop does not require an explicit startTransition because actions are already wrapped in one . This boundary is what distinguishes an optimistic update from a regular state update: the optimistic state is scoped to the transition, and it disappears when the transition completes. A dispatch outside a transition logs a warning and renders for one frame before reverting, which looks like a flicker rather than an update .
The trade-off. useOptimistic assumes the action will succeed most of the time. When it fails, the optimistic entry vanishes. If the failure is invisible—a silent revert with no error message—the user sees their action disappear and does not know why. The hook does not surface errors. Pairing it with useActionState for error state, or a toast notification in the catch branch, is the production pattern . The hook provides the speed; the developer provides the honesty.
a. The signature and the transition boundary
The hook accepts two arguments: the canonical state and a pure update function. It returns the optimistic state and a dispatch function. The dispatch must be called inside a transition or an action, and the update function must be pure—no side effects, no network calls, no mutations of its arguments.
// app/comments/comment-list.tsx
'use client';
import { useOptimistic, useTransition } from 'react';
import { createComment } from '@/app/actions';
interface Comment {
id: string;
body: string;
pending?: boolean;
}
export function CommentList({
initialComments,
postId,
}: {
initialComments: Comment[];
postId: string;
}) {
// useTransition provides the boundary that scopes the optimistic state.
const [isPending, startTransition] = useTransition();
// The update function merges the optimistic comment into the list.
// It must be pure: no side effects, no async, no mutation.
const [optimisticComments, addOptimisticComment] = useOptimistic(
initialComments,
(current, newComment: Comment) => [
...current,
{ ...newComment, pending: true },
]
);
const handleSubmit = (formData: FormData) => {
const body = formData.get('body') as string;
// The dispatch must be inside a transition.
// If it is called outside, React warns and the value reverts.
startTransition(async () => {
addOptimisticComment({ id: crypto.randomUUID(), body });
await createComment(postId, formData);
});
};
return (
<div>
<ul>
{optimisticComments.map(comment => (
<li key={comment.id} style={{ opacity: comment.pending ? 0.5 : 1 }}>
{comment.body}
{comment.pending && <small> Sending…</small>}
</li>
))}
</ul>
<form action={handleSubmit}>
<textarea name="body" required disabled={isPending} />
<button type="submit" disabled={isPending}>
{isPending ? 'Posting…' : 'Comment'}
</button>
</form>
</div>
);
}
The pending flag inside the optimistic comment is a UI detail, not part of the canonical data. The update function adds it so the component can dim the entry and show the “Sending…” label. When the action settles, the optimistic entry is replaced by the canonical state, which does not have the pending property. The transition between the two is invisible if the server confirmed the change; if the action threw, the optimistic entry disappears entirely and the error path takes over .
b. The failure mode: rollback and the invisible revert
The hook reverts automatically when the action throws. This is the contract, and it is also the source of the most common production bug: the revert is silent. The user’s optimistic entry disappears, the list returns to its previous state, and nothing tells the user that the action failed. The fix is not in the hook; it is in the error handling around it.
// app/comments/comment-list.tsx — with error surfacing
'use client';
import { useOptimistic, useTransition } from 'react';
import { useActionState } from 'react';
import { createComment } from '@/app/actions';
export function CommentList({
initialComments,
postId,
}: {
initialComments: Comment[];
postId: string;
}) {
// useActionState provides the error surface.
// The error is returned from the Server Action, not thrown.
const [state, formAction] = useActionState(createComment, { error: null });
const [isPending, startTransition] = useTransition();
const [optimisticComments, addOptimisticComment] = useOptimistic(
initialComments,
(current, newComment: Comment) => [
...current,
{ ...newComment, pending: true },
]
);
const handleSubmit = (formData: FormData) => {
const body = formData.get('body') as string;
startTransition(async () => {
// Dispatch the optimistic entry.
addOptimisticComment({ id: crypto.randomUUID(), body });
// Invoke the action. If it returns an error instead of throwing,
// the optimistic entry reverts when the transition settles,
// and the error renders from useActionState.
formAction(formData);
});
};
return (
<div>
{state.error && <p role="alert">{state.error}</p>}
<ul>
{optimisticComments.map(comment => (
<li key={comment.id} style={{ opacity: comment.pending ? 0.5 : 1 }}>
{comment.body}
</li>
))}
</ul>
<form action={handleSubmit}>
<textarea name="body" required disabled={isPending} />
<button type="submit" disabled={isPending}>Comment</button>
</form>
</div>
);
}
The Server Action must return known errors rather than throw them. A thrown error cancels the transition and triggers the error boundary, which unmounts the form and loses the user’s input. A returned error populates useActionState, keeps the form interactive, and lets the optimistic entry revert cleanly .
c. When not to use useOptimistic
The hook is designed for high-success, low-risk interactions. The React documentation’s examples are message sending and form submissions. The patterns that break are the ones where the optimistic state can be catastrophically wrong.
Destructive actions. A delete that shows the item gone before the server confirms has no safe rollback if the server succeeds but the response is lost. The item is gone from the UI, the user believes it is deleted, and the next page load reveals it still exists. Without an undo mechanism, optimistic deletes are a trust violation waiting to happen .
Financial or inventory data. Showing a balance that has not been confirmed can lead the user to act on money that does not exist. The brief incorrect value is worse than the wait.
Actions with server-only validation. If the server is the only layer that can reject the input—a uniqueness constraint, a permission check, an inventory count—the optimistic entry may flash and revert. The user sees their action succeed and then fail in the same interaction. The experience is worse than a pending spinner .
The decision rule is simple: use useOptimistic when the client can predict the server’s response with high confidence. Do not use it when the server might say no for reasons the client cannot check.
Complete Example Session
// ============================================
// PART 1: THE SERVER ACTION WITH ERROR RETURN
// ============================================
// app/actions.ts
'use server';
import { db } from '@/lib/db';
import { auth } from '@/lib/auth';
interface CommentState {
error: string | null;
}
export async function createComment(
postId: string,
formData: FormData
): Promise<CommentState> {
const session = await auth();
if (!session?.user) {
throw new Error('Unauthorized'); // Unknown error: throw
}
const body = formData.get('body') as string;
if (!body || body.trim().length === 0) {
return { error: 'Comment cannot be empty' }; // Known error: return
}
await db.comment.create({
data: { postId, body: body.trim(), authorId: session.user.id },
});
return { error: null };
}
// ============================================
// PART 2: THE OPTIMISTIC COMPONENT
// ============================================
// app/comments/comment-section.tsx
'use client';
import { useOptimistic, useTransition } from 'react';
import { useActionState } from 'react';
import { createComment } from '@/app/actions';
interface Comment {
id: string;
body: string;
pending?: boolean;
}
export function CommentSection({
postId,
initialComments,
}: {
postId: string;
initialComments: Comment[];
}) {
const [state, formAction] = useActionState(createComment.bind(null, postId), {
error: null,
});
const [isPending, startTransition] = useTransition();
const [optimisticComments, addOptimisticComment] = useOptimistic(
initialComments,
(current, newComment: Comment) => [
...current,
{ ...newComment, pending: true },
]
);
const handleSubmit = (formData: FormData) => {
const body = formData.get('body') as string;
startTransition(async () => {
addOptimisticComment({ id: crypto.randomUUID(), body });
formAction(formData);
});
};
return (
<div>
{state.error && <p role="alert">{state.error}</p>}
<ul>
{optimisticComments.map(comment => (
<li key={comment.id} style={{ opacity: comment.pending ? 0.5 : 1 }}>
{comment.body}
{comment.pending && <small> (Sending…)</small>}
</li>
))}
</ul>
<form action={handleSubmit}>
<textarea name="body" disabled={isPending} />
<button type="submit" disabled={isPending}>
{isPending ? 'Posting…' : 'Comment'}
</button>
</form>
</div>
);
}
// ============================================
// PART 3: THE DISPATCH OUTSIDE TRANSITION (WARNING)
// ============================================
// ❌ This renders for one frame and reverts.
// React logs: "An optimistic state update occurred
// outside a Transition or Action."
function BrokenLike({ liked }: { liked: boolean }) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
const handleClick = async () => {
setOptimisticLiked(!optimisticLiked); // Outside transition
await likePost();
};
return <button onClick={handleClick}>{optimisticLiked ? '❤️' : '🤍'}</button>;
}
// ✅ The dispatch is inside the action prop, which is a transition.
function WorkingLike({ liked }: { liked: boolean }) {
const [optimisticLiked, setOptimisticLiked] = useOptimistic(liked);
async function toggleLike() {
setOptimisticLiked(!optimisticLiked); // Inside action prop
await likePost();
}
return <form action={toggleLike}><button>{optimisticLiked ? '❤️' : '🤍'}</button></form>;
}
// ============================================
// PART 4: THE DOUBLE-COUNT BUG
// ============================================
// A common bug when the base state is updated manually
// inside the transition while the optimistic entry is still queued.
//
// The transition has not settled, so the optimistic entry is still
// in the queue. If the base state is also updated, the rendered value
// is base + optimistic = double count.
//
// ✅ Fix: do not update the base state manually inside the transition.
// Let revalidatePath (or the parent's state update) refresh the base
// after the transition settles.
// ============================================
// PART 5: THE PURE UPDATE FUNCTION
// ============================================
// The update function must be pure. It runs on every render
// while the transition is pending.
export function TodoList({ todos }: { todos: Todo[] }) {
const [optimisticTodos, addTodo] = useOptimistic(
todos,
(current, newTodo: Todo) => [...current, { ...newTodo, pending: true }]
);
// ❌ The update function must not mutate `current`.
// ❌ It must not perform deep clones of large trees.
// ✅ It must return a new array or object.
return null;
}
// ============================================
// PART 6: COMBINING WITH useActionState FOR ERRORS
// ============================================
// The pattern: useActionState for error state,
// useOptimistic for immediate UI,
// useTransition for the boundary.
// The form action is the handleSubmit function,
// not the Server Action directly. The Server Action is
// invoked inside the transition via formAction.
// ============================================
// PART 7: SERVER ACTIONS WITH BIND
// ============================================
// Binding the postId to the action:
const boundAction = createComment.bind(null, postId);
// Then wrapping with useActionState:
const [state, formAction] = useActionState(boundAction, { error: null });
// The bound postId is not part of the form data.
// It is part of the action reference.
// ============================================
// PART 8: VERIFICATION CHECKLIST
// ============================================
// [ ] The dispatch is inside startTransition or an action prop.
// [ ] The update function is pure.
// [ ] The Server Action returns known errors, throws unknown errors.
// [ ] The optimistic entry has a pending flag for visual differentiation.
// [ ] The error state renders when the action returns an error.
// [ ] The base state is not manually updated inside the transition.
// [ ] The interaction is high-success (not a destructive action).
The ten parts covered the signature, the transition boundary, the rollback contract, the error pairing, the double-count bug, and the checklist. The through-line is that useOptimistic is a rendering illusion scoped to a transition. The hook does not make the server faster; it makes the wait feel like progress.
Quick Reference
Hook signature
| Element | Type | Meaning |
|---|---|---|
state | State | Canonical state from the server |
updateFn | (current, optimisticValue) => State | Pure merge function |
optimisticState | State | The merged state while pending |
addOptimistic | (value) => void | Dispatch; must be inside transition |
The transition boundary
| Context | Requires explicit startTransition? | Why |
|---|---|---|
Action prop (<form action={fn}>) | No | React wraps actions in transitions |
Event handler (onClick) | Yes | The handler is not a transition |
Inside useTransition | No | Already scoped |
When to use and when to avoid
| Scenario | Use useOptimistic? | Why |
|---|---|---|
| Comment post | Yes | High success, append-only |
| Like toggle | Yes | High success, reversible |
| Delete | No | No safe rollback without undo |
| Payment | No | Financial data cannot be wrong |
| Server-only validation | No | Client cannot predict rejection |
Best Practices
✅ Do This:
// Dispatch inside a transition
startTransition(() => addOptimistic(value)); // ✅
// Keep the update function pure
(state, value) => [...state, value] // ✅
// Pair with useActionState for error display
const [state, formAction] = useActionState(action, initialState); // ✅
// Differentiate pending entries visually
{ opacity: comment.pending ? 0.5 : 1 } // ✅
// Disable the button during pending
<button disabled={isPending}>Send</button> // ✅
❌ Don’t Do This:
// Dispatch outside a transition
addOptimistic(value); // in a plain onClick handler // ❌
// Mutate the canonical state inside the transition
setCanonical([...canonical, item]); // while optimistic is queued // ❌
// Use for destructive actions without undo
addOptimistic({ id, deleted: true }); // ❌
// Swallow the error and let the optimistic entry revert silently
try { await action(); } catch { /* nothing */ } // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Optimistic value flickers and reverts | Dispatch outside a transition | Wrap in startTransition or use an action prop |
| Double count during transition | Base state updated manually while optimistic queued | Let the server revalidation update the base after settling |
| Error is invisible | The action throws and the entry reverts silently | Pair with useActionState or a toast |
| Update function causes frame drops | Deep clone of large state | Keep the function O(n) or better |
| Optimistic delete is wrong | No undo mechanism; server confirmed but client missed it | Do not use optimistic UI for deletes without undo |
Real-World Examples
1. Optimistic comment
addOptimisticComment({ id: crypto.randomUUID(), body });
startTransition(() => formAction(formData));
2. Like toggle inside action prop
<form action={async () => { setOptimisticLiked(!liked); await like(); }}>
3. Pending visual
<li style={{ opacity: comment.pending ? 0.5 : 1 }}>{comment.body}</li>
4. Pure merge function
(current, newItem) => [...current, { ...newItem, pending: true }]
5. Error pairing
{state.error && <p role="alert">{state.error}</p>}
6. Transition with error catch
startTransition(async () => { addOptimistic(v); try { await action(v); } catch { toast.error('Failed'); } });
7. Disable during pending
<button disabled={isPending}>{isPending ? 'Sending…' : 'Send'}</button>
8. Rollback is automatic
// The optimistic entry disappears when the transition settles.
// No manual revert code.
9. Bind server context
const bound = createComment.bind(null, postId);
10. Do not use for delete
// Optimistic delete requires an undo mechanism.
// Without it, the user trusts a deletion that may not be reversible.
Visual
The Optimistic Lifecycle
┌──────────────────────────────────────────────────────────────┐
│ FROM DISPATCH TO RECONCILIATION │
│ │
│ User submits │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ addOptimistic │ Inside a transition │
│ │ called │ optimisticState = updateFn(...) │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ │
│ │ UI renders the │ The user sees the result │
│ │ optimistic state│ before the server confirms │
│ └────────┬────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Action succeeds │ │ Action throws │ │
│ │ │ │ │ │
│ │ Transition │ │ Transition │ │
│ │ settles │ │ settles │ │
│ │ │ │ │ │
│ │ Canonical state │ │ Optimistic │ │
│ │ replaces the │ │ entry reverts │ │
│ │ optimistic │ │ to canonical │ │
│ └─────────────────┘ └─────────────────┘ │
│ │
│ The optimistic state exists only while the transition │
│ is pending. The settle is the reconciliation. │
└──────────────────────────────────────────────────────────────┘
The Transition Boundary
┌──────────────────────────────────────────────────────────────┐
│ WHERE THE DISPATCH IS ALLOWED │
│ │
│ Action Prop Event Handler │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ <form action={fn}> │ │ onClick={() => { │ │
│ │ │ │ addOptimistic() │ │
│ │ fn is a transition │ │ }} │ │
│ │ │ │ │ │
│ │ addOptimistic │ │ ❌ Outside a │ │
│ │ inside fn works │ │ transition. │ │
│ │ │ │ Reverts in one │ │
│ │ ✅ │ │ frame. │ │
│ └────────────────────┘ └────────────────────┘ │
│ │
│ Wrap the event handler in startTransition or │
│ useTransition to create the boundary. │
└──────────────────────────────────────────────────────────────┘
Silent Revert vs Visible Error
┌──────────────────────────────────────────────────────────────┐
│ THE ROLLBACK CONTRACT │
│ │
│ Without error surface With error surface │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ Optimistic entry │ │ Optimistic entry │ │
│ │ appears │ │ appears │ │
│ └─────────┬──────────┘ └─────────┬──────────┘ │
│ │ │ │
│ ▼ ▼ │
│ ┌────────────────────┐ ┌────────────────────┐ │
│ │ Action fails │ │ Action returns │ │
│ │ │ │ { error: '...' } │ │
│ │ Entry disappears │ │ Entry reverts │ │
│ │ No message │ │ Error renders │ │
│ │ User confused │ │ User understands │ │
│ └────────────────────┘ └────────────────────┘ │
│ │
│ The hook provides the revert. The developer provides │
│ the explanation. │
└──────────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Hook signature | useOptimistic(state, updateFn) |
| Returns | [optimisticState, addOptimistic] |
| Update function | Pure; (current, optimisticValue) => State |
| Dispatch placement | Inside startTransition or an action prop |
| Rollback | Automatic when the transition settles |
| Error display | Not built-in; pair with useActionState or toast |
| Best for | High-success, low-risk mutations |
| Avoid for | Deletes without undo, financial data, server-only validation |
Key takeaways:
- The transition is the lifetime. The optimistic state exists only while a transition is pending. Dispatching outside a transition produces a flicker, not an update. Action props are transitions; event handlers must be wrapped explicitly .
- The update function must be pure and fast. It runs on every render while the transition is pending. Deep clones of large trees drop frames. Shallow spreads and O(n) operations keep the optimistic window smooth .
- The revert is silent by default. When the action fails, the optimistic entry disappears. Pair the hook with
useActionStatefor inline errors or a toast in the catch branch. The user must know why their action did not stick . - Do not use it for destructive actions. A delete that shows the item gone before the server confirms has no safe rollback if the confirmation is lost. Without an undo mechanism, optimistic deletes are a trust violation .
- Do not manually update the base state inside the transition. The optimistic entry is still queued, and the rendered value becomes base + optimistic. Let the server revalidation update the base after the transition settles .
Remember: useOptimistic is a rendering illusion scoped to a transition. It makes the wait invisible by showing the expected result before the server confirms it. The hook does not validate, authorize, or error-handle. It merges a value into the state and reverts when the transition ends. The developer decides what to merge, when to dispatch, and how to explain the revert. The hook provides the speed; the honesty is still yours.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!