React useOptimistic and useFormStatus: Instant UI Feedback in React 19
Optimistic state that reverts by itself when the Action fails, plus form pending status read from inside the form instead of lifted state.

Quick Summary
Optimistic UI shows the result before the server confirms it, and useOptimistic is the React 19 hook that makes that safe. It takes the real value and an optional reducer, returns a temporary value plus a setter, and guarantees the temporary value lives only as long as the surrounding Action. When the Action finishes, the component renders the real value again — the new one on success, the unchanged one on failure. There is no separate "clear the optimistic state" step and no window in which stale optimism survives.
useFormStatus is the other half: a read-only hook that reports the last submission of the nearest parent <form>. It returns pending, data, method, and action, which is enough to disable a submit button, show a spinner, or echo the submitted values without lifting state out of the form.
Both hooks are designed around Actions — functions passed to a form's action prop or called inside startTransition. Used outside that context they misbehave in specific ways: an optimistic update outside an Action briefly renders and then reverts with a warning, and useFormStatus returns pending: false forever when it is called in the same component that renders the form.
Basic Syntax & Signature
import { useOptimistic } from "react";
import { useFormStatus } from "react-dom";
// value = the real, server-confirmed value. reducer is optional and pure.
const [optimisticValue, setOptimistic] = useOptimistic(value, reducer?);
// Must be rendered inside <form>. Returns submission status, never args.
const { pending, data, method, action } = useFormStatus();A like button is the smallest useful case:
function LikeButton({ likes, onLike }: { likes: number; onLike: () => Promise<void> }) {
const [optimisticLikes, addOptimisticLike] = useOptimistic(
likes,
(current, delta: number) => current + delta
);
return (
<form
action={async () => {
addOptimisticLike(1);
await onLike();
}}
>
<SubmitLike count={optimisticLikes} />
</form>
);
}
function SubmitLike({ count }: { count: number }) {
// Inside the form, so it reads the form's status.
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
♥ {count}
</button>
);
}The setter is only valid inside an Action. React treats the call as "show this until the Action settles", and because the real value comes from the hook argument, the two converge in a single render when the Action completes.
// Add-todo with a reducer keeps optimistic inserts on top of fresh data.
const [optimisticTodos, addOptimisticTodo] = useOptimistic(
todos,
(current: Todo[], newTitle: string): Todo[] => [
...current,
{ id: `temp-${crypto.randomUUID()}`, title: newTitle, pending: true },
]
);Key Comparison Table
| Aspect | useOptimistic | useFormStatus |
|---|---|---|
| Package | react | react-dom |
| Direction | Writes a temporary value | Reads submission status |
| Arguments | (value, reducer?) | None |
| Returns | [optimisticValue, setOptimistic] | { pending, data, method, action } |
| Valid call site | Inside an Action or transition | Anywhere inside a <form> |
Persists across await | Yes, until the Action settles | Yes, until the submission ends |
Used in the same component as <form> | Fine | Returns pending: false |
| Requires a server | No | No |
| Risk if misused | Warning, brief flash, no revert on error | Silent false negative |
Works with useActionState | Yes, complements it | Yes |
Practical Edge Cases & Deep Dives
1. The optimistic update that must roll back
type Message = { id: string; text: string; status: "sent" | "sending" | "failed" };
function Thread({ messages, send }: { messages: Message[]; send: (text: string) => Promise<void> }) {
const [optimistic, addOptimistic] = useOptimistic(
messages,
(current, text: string) => [
...current,
{ id: `tmp-${text}`, text, status: "sending" as const },
]
);
const [error, setError] = useState<string | null>(null);
return (
<form
action={async (formData: FormData) => {
const text = String(formData.get("text") ?? "");
if (!text) return;
addOptimistic(text);
try {
await send(text);
setError(null);
} catch {
// No manual rollback: not updating `messages` is the rollback.
setError("Message failed to send.");
}
}}
>
<ul>
{optimistic.map((m) => (
<li key={m.id} aria-busy={m.status === "sending"}>
{m.text}
</li>
))}
</ul>
<input name="text" />
<button type="submit">Send</button>
{error && <p role="alert">{error}</p>}
</form>
);
}The rollback is implicit and that is the design: the optimistic value is derived from messages, so if the Action throws and the parent never updates messages, the next render shows the original list. Any code that also pushes into a local copy on failure will double-apply or resurrect the failed item.
2. useFormStatus in the wrong component
// Wrong: the hook is in the component that renders the form.
function BadForm({ action }: { action: (fd: FormData) => Promise<void> }) {
const { pending } = useFormStatus(); // always false here
return (
<form action={action}>
<button disabled={pending}>Save</button>
</form>
);
}
// Right: a child rendered inside the form reads the form's status.
function SubmitButton({ label }: { label: string }) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending} aria-disabled={pending}>
{pending ? "Saving…" : label}
</button>
);
}
function GoodForm({ action }: { action: (fd: FormData) => Promise<void> }) {
return (
<form action={action}>
<SubmitButton label="Save" />
</form>
);
}The hook reads the context of the nearest parent <form> element, and the component that renders that element sits above it. This is the most common reason a "loading state never shows" bug reaches production, and it fails silently rather than with an error.
3. Pending values from data
function SaveBar() {
const { pending, data, method } = useFormStatus();
const title = pending ? String(data?.get("title") ?? "") : "";
return (
<div aria-live="polite">
{pending ? `Saving "${title}" via ${method?.toUpperCase()}…` : "All changes saved"}
</div>
);
}data is the FormData of the in-flight submission, which lets you render what is being sent instead of a generic spinner. It is null when nothing is submitting, and method is 'get' or 'post' — a default <form> posts as get, which surprises people writing POST-only handlers.
4. Optimistic state combined with useActionState
import { useActionState, useOptimistic } from "react";
type State = { error?: string };
async function renameAction(_prev: State, formData: FormData): Promise<State> {
const name = String(formData.get("name") ?? "");
if (name.length < 3) return { error: "Name is too short." };
await fetch("/api/profile", { method: "POST", body: JSON.stringify({ name }) });
return {};
}
function Rename({ current }: { current: string }) {
const [state, formAction, isPending] = useActionState(renameAction, {});
const [optimisticName, setOptimisticName] = useOptimistic(current);
return (
<form
action={(fd) => {
setOptimisticName(String(fd.get("name") ?? current));
return formAction(fd);
}}
>
<h2>{optimisticName}</h2>
<input name="name" defaultValue={current} disabled={isPending} />
<button disabled={isPending}>Rename</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}useActionState owns validation results and the authoritative value; useOptimistic owns the instant heading. The optimistic value reverts when the action settles without a successful rename, so a rejected name shows the old heading with the error beside it.
5. Why the optimistic setter warns outside an Action
function Counter() {
const [count, setCount] = useState(0);
const [optimistic, setOptimistic] = useOptimistic(count);
return (
<button
onClick={() => {
// Warning in development: "An optimistic state update occurred
// outside a transition or action."
setOptimistic(count + 1);
}}
>
{optimistic}
</button>
);
}Outside an Action nothing defines when the optimistic value should end, so React renders it, then immediately falls back to count. The fix is either an actual Action (startTransition(async () => { setOptimistic(...); await save(); })) or plain useState when there is no server round trip to hide.
6. Multiple optimistic updates in one Action
function CartItem({ item, remove }: { item: Item; remove: () => Promise<void> }) {
const [optimisticItem, hideItem] = useOptimistic(
item,
(current: Item | null) => null // reducer may return null: the row disappears
);
if (!optimisticItem) return null;
return (
<form
action={async () => {
hideItem(null);
await remove();
}}
>
<span>{optimisticItem.name}</span>
<SubmitRemove />
</form>
);
}
function SubmitRemove() {
const { pending } = useFormStatus();
return <button disabled={pending}>Remove</button>;
}Returning null from the reducer is supported because the optimistic value can be any type, including one that makes the component render nothing. Eleven actions fired in a row each get their own optimistic scope, and React applies them in order; the UI converges to the real value once the last one settles.
Common Compilation/Runtime Mistakes
| Symptom | Cause | Fix |
|---|---|---|
| "Optimistic state update outside a transition" warning | Setter called in a click handler | Wrap in an Action or startTransition |
| Count jumps then snaps back on error | Expected behaviour | Render an error message; do not re-add locally |
useFormStatus().pending always false | Hook used in the form's own component | Move it to a child of <form> |
data is null during submission | Child rendered outside the form | Fix the component tree |
| Duplicate items after a failed Action | Optimistic insert also written to local state | Derive the list only from the hook argument |
| Optimistic value survives a route change | Hook value that never changes | Pass state that the Action updates |
| Reducer mutates the array | Impure reducer | Return a new array |
| Pending button stays disabled | Submission never settles | Ensure the action returns or throws |
key collisions between temp and real rows | Optimistic id reused | Prefix temporary ids and reconcile by id |
| Effects never fire for the optimistic render | Optimistic state does not commit as a separate effect cycle | Do side effects in the Action, not in useEffect |
The pairing is deliberate: useOptimistic changes what the user sees, useFormStatus changes what the user can do while the change is in flight. Neither replaces useActionState for validation results, and none of them work as intended when the update escapes the Action that scopes it.
Try matching browser tools
All toolsSmall utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related React guides
All React guidesReact Profiler API: Measuring Render Timings and Identifying Wasted Re-Renders
actualDuration versus baseDuration, phase names that tell you who triggered a commit, and how to ship the numbers without flooding a backend.
React with TypeScript: Generic Components, PropsWithChildren, and Event Types
Generic props that infer from data, PropsWithChildren instead of React.FC, and element-scoped event types that keep currentTarget typed.
React useTransition and useDeferredValue: Non-Blocking Concurrent UI Updates
Transitions let React throw away background work when typing arrives. Which hook defers what, and why a controlled input must never be transitioned.
React.lazy and Code Splitting: Route Chunks, Preloading, and Suspense
Where the split points belong, how to preload on intent, and how to recover when a stale chunk 404s after a deployment.
More in React
All React guidesThe guides filed next to this one in React, in library order.