Sub topic 9
Pending and optimistic UI with useFormStatus, useTransition and useOptimistic
This chapter assumes you can write React components with hooks, and that you have defined a Server Function and called it from a form, as covered earlier in this tutorial. It shows how to give users feedback while a Server Function runs, and how to show the expected result before the server confirms it.
Why pending state needs its own tools
A Server Function call is a network request. Between the click and the response, the interface should show that something is happening. It should also stop the user from submitting twice. React provides several hooks for this. They overlap, so the main skill is picking the one that fits where your code lives.
| Hook | Where it works | What it gives you |
|---|---|---|
| `useActionState` | Component that owns the form | Returned state plus an `isPending` flag |
| `useFormStatus` | Component rendered inside a `<form>` | `pending`, `data`, `method`, `action` of the parent form |
| `useTransition` | Any Client Component, such as an event handler | `isPending` and `startTransition` |
| `useOptimistic` | Any Client Component, called within an action or transition | A temporary copy of state that reverts when the action ends |
The first row was covered in the previous chapter. The rest are covered here.
useFormStatus: pending state for child components
useFormStatus is exported from react-dom, not react. It reports the status of the closest parent <form>. This lets a reusable button disable itself without receiving a prop from the form's owner.
// app/SubmitButton.js
'use client';
import { useFormStatus } from 'react-dom';
export function SubmitButton({ children }) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending} aria-disabled={pending}>
{pending ? 'Saving…' : children}
</button>
);
}Use it in a form that is a Server Component. Only the button needs 'use client', so the rest of the page stays on the server:
// app/page.js (a Server Component)
import { db } from './db';
import { SubmitButton } from './SubmitButton';
export default function Page() {
async function createNote(formData) {
'use server';
await db.notes.insert({ title: formData.get('title') });
}
return (
<form action={createNote}>
<input name="title" required />
<SubmitButton>Add note</SubmitButton>
</form>
);
}The returned object has four fields:
pendingistruewhile the form's action is running.datais theFormDatabeing submitted, ornullwhen idle.methodis'get'or'post'.actionis the function passed to the form'sactionprop.
The most common mistake
useFormStatus does not read the form that your own component renders. It only reads a form that is an ancestor. This code never shows a pending state:
'use client';
import { useFormStatus } from 'react-dom';
// Wrong: the form is rendered here, not above this component.
export function BrokenForm({ action }) {
const { pending } = useFormStatus(); // always false
return (
<form action={action}>
<button disabled={pending}>Save</button>
</form>
);
}Move the hook into a child component, such as SubmitButton above. If the same component owns the form and the action, use the isPending value from useActionState instead.
useTransition: pending state outside forms
Not every Server Function call comes from a form. A delete button, a toggle, or a drag handler calls the function from an event handler. Wrapping the call in startTransition lets React track it and gives you isPending.
// app/DeleteButton.js
'use client';
import { useTransition } from 'react';
import { deleteNote } from './actions';
export function DeleteButton({ noteId }) {
const [isPending, startTransition] = useTransition();
return (
<button
disabled={isPending}
onClick={() => {
startTransition(async () => {
await deleteNote(noteId);
});
}}
>
{isPending ? 'Deleting…' : 'Delete'}
</button>
);
}A function passed to startTransition that returns a Promise is called an Action. isPending stays true until the Promise settles and any resulting UI update has rendered.
There is one caveat. Code after an await inside the transition function runs outside the transition's scope. State updates there are not marked as transition updates unless you wrap them in another startTransition:
startTransition(async () => {
const result = await saveDraft(draftId);
startTransition(() => {
setStatus(result.status); // wrapped again because it follows an await
});
});Also note that Transitions are not queued independently. If you start a second Server Function call while the first is pending, React runs them in order. This is also why you should disable the control while isPending is true.
useOptimistic: show the result before the server answers
An optimistic update shows the expected outcome immediately and corrects it if the server disagrees. useOptimistic takes the real state and an update function, and returns the state to render plus a function that applies a temporary change.
// app/NoteList.js
'use client';
import { useOptimistic } from 'react';
import { createNote } from './actions';
export function NoteList({ notes }) {
const [optimisticNotes, addOptimisticNote] = useOptimistic(
notes,
(currentNotes, newNote) => [...currentNotes, newNote]
);
async function formAction(formData) {
const title = String(formData.get('title') ?? '').trim();
if (title.length === 0) return;
addOptimisticNote({ id: crypto.randomUUID(), title, sending: true });
await createNote(formData);
}
return (
<>
<ul>
{optimisticNotes.map((note) => (
<li key={note.id} style={{ opacity: note.sending ? 0.5 : 1 }}>
{note.title}
</li>
))}
</ul>
<form action={formAction}>
<input name="title" />
<button type="submit">Add note</button>
</form>
</>
);
}This example uses the single-argument createNote(formData) from earlier in the tutorial, not the prevState version. The parent Server Component fetches notes and passes them as a prop.
What happens step by step
- The user submits the form. React runs
formActioninside a transition. addOptimisticNoteproduces a temporary list. The new note appears at once, dimmed.await createNote(formData)sends the request to the server.- The server inserts the note. The framework then re-renders the page and passes a fresh
notesprop. - When the action finishes, the optimistic state is discarded and React renders the real
notes. The temporary item is replaced by the saved one.
Rules that prevent bugs
- Call the setter only inside an Action: a form
action, or a function passed tostartTransition. Calling it elsewhere logs a warning and the update does not behave as intended. - The optimistic value is temporary by design. It is always recomputed from the current real state plus the pending updates, so it never drifts from the source of truth.
- The
keyof the temporary item will not match the saved item'skey. React unmounts one and mounts the other. This is fine for lists, but avoid keeping local state, such as focus or input text, inside optimistic items. - Never put the optimistic value into your database or into other state. Treat it as display-only.
Failures: what the user sees when the call fails
When the Server Function fails, the optimistic state reverts when the action ends. Whether the user learns why depends on how you report the failure.
- If the function throws, the action's Promise rejects. The optimistic item disappears, and the error propagates to the nearest error boundary. Use this for unexpected failures.
- If the function returns an error value, as in the
useActionStatepattern, the optimistic item disappears and you render the returned message.
A common combination uses useActionState for the result and useOptimistic for the preview:
// app/NoteForm.js
'use client';
import { useActionState, useOptimistic } from 'react';
import { createNote } from './actions'; // the (prevState, formData) version
export function NoteForm({ notes }) {
const [state, formAction] = useActionState(createNote, { error: null });
const [optimisticNotes, addOptimisticNote] = useOptimistic(
notes,
(current, title) => [...current, { id: `pending-${title}`, title }]
);
function submit(formData) {
addOptimisticNote(String(formData.get('title') ?? ''));
formAction(formData);
}
return (
<form action={submit}>
<ul>
{optimisticNotes.map((n) => (
<li key={n.id}>{n.title}</li>
))}
</ul>
<input name="title" />
<button type="submit">Add note</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}If validation fails on the server, createNote returns { error: 'Title is required.' }. The temporary item vanishes and the message appears. The user sees the item flash, so validate obvious problems, such as an empty title, on the client before calling addOptimisticNote.
Choosing between the hooks
Start from the shape of your UI.
- The button is inside a form and lives in its own component:
useFormStatus. - The component owns the form and also needs the returned state:
useActionStateand itsisPending. - The call comes from a click, change, or other event:
useTransition. - The user should see the result before the server responds: add
useOptimisticon top of any of the above.
These hooks combine well. A pending flag tells the user the request is in flight, and an optimistic value shows what the screen will probably look like afterwards. Neither changes the security model. The server still validates and authorizes every call, whatever the client displayed.
Edge cases
- Progressive enhancement. With a Server Function passed directly to
<form action>, the form can submit before JavaScript loads.useFormStatusanduseOptimisticonly work after hydration, so the page must still behave correctly without them. - Form reset. After a function passed to
<form action>completes, React resets uncontrolled fields. If you want to keep the input after a validation error, return the submitted values in your state and use them asdefaultValue. - Double submit. Disabling the button prevents most duplicates, but a user can press Enter in a text field. Make the server side tolerate repeats where it matters, for example with a unique constraint.
- Stale data. The optimistic list is based on the
notesprop at render time. If your framework does not refresh that prop after the mutation, the real list stays stale once the action ends. Frameworks provide a way to revalidate data after a mutation. Check your framework's documentation.
Exercise
A teammate writes a Client Component that renders <form action={save}> and, in the same component, calls const { pending } = useFormStatus() to disable the submit button. The button never disables. Why, and what are two ways to fix it?
Show answer
useFormStatus reads the status of a parent <form>, not a form rendered by the same component, so pending is always false. Fix it by moving the button into a child component that calls useFormStatus, or by using the isPending value returned as the third item of useActionState in the component that owns the form.
Exercise
In the NoteList example, the Server Function throws an error after addOptimisticNote was called. What happens to the temporary note, and where does the error go?
Show answer
The temporary note disappears when the action ends, because optimistic state is only held while the action is pending and then replaced by the real notes prop, which does not contain the note. The thrown error rejects the action's Promise and propagates to the nearest error boundary.
Exercise
Write the body of a click handler that calls deleteNote(noteId) and tracks pending state, using the hook designed for non-form calls.
Show answer
Get const [isPending, startTransition] = useTransition(); in the component. In the handler, call startTransition(async () => { await deleteNote(noteId); }); and use isPending to disable the button or change its label.