Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

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.

~4 min readReact
#React#React 19#Hooks
3D illustration of optimistic UI state cards with pending form indicators reconciling against async server responses

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

tsx
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:

tsx
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.

tsx
// 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

AspectuseOptimisticuseFormStatus
Packagereactreact-dom
DirectionWrites a temporary valueReads submission status
Arguments(value, reducer?)None
Returns[optimisticValue, setOptimistic]{ pending, data, method, action }
Valid call siteInside an Action or transitionAnywhere inside a <form>
Persists across awaitYes, until the Action settlesYes, until the submission ends
Used in the same component as <form>FineReturns pending: false
Requires a serverNoNo
Risk if misusedWarning, brief flash, no revert on errorSilent false negative
Works with useActionStateYes, complements itYes

Practical Edge Cases & Deep Dives

1. The optimistic update that must roll back

tsx
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

tsx
// 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

tsx
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

tsx
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

tsx
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

tsx
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

SymptomCauseFix
"Optimistic state update outside a transition" warningSetter called in a click handlerWrap in an Action or startTransition
Count jumps then snaps back on errorExpected behaviourRender an error message; do not re-add locally
useFormStatus().pending always falseHook used in the form's own componentMove it to a child of <form>
data is null during submissionChild rendered outside the formFix the component tree
Duplicate items after a failed ActionOptimistic insert also written to local stateDerive the list only from the hook argument
Optimistic value survives a route changeHook value that never changesPass state that the Action updates
Reducer mutates the arrayImpure reducerReturn a new array
Pending button stays disabledSubmission never settlesEnsure the action returns or throws
key collisions between temp and real rowsOptimistic id reusedPrefix temporary ids and reconcile by id
Effects never fire for the optimistic renderOptimistic state does not commit as a separate effect cycleDo 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 tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.