Sub topic 9
Pending and optimistic UI with useFormStatus, useTransition and useOptimistic
This chapter assumes you can write Server Functions, call them from forms and event handlers, and use useActionState. A Server Function call is a network round trip, so the interface needs to show that work is in progress. It can also show the expected result before the server confirms it.
Three hooks, three situations
Each hook fits a different place in your component tree.
| Hook | Use it when | Where it runs |
|---|---|---|
| `useFormStatus` | A child component, such as a submit button, needs to know whether its parent form is submitting | Client Component inside a `<form>` |
| `useTransition` | You call a Server Function from an event handler instead of a form | Client Component |
| `useOptimistic` | You want to show the expected result immediately and replace it with the real result later | Client Component |
useActionState already returns an isPending flag for the form it wraps. The other hooks cover the cases where you don't own that form, or where no form exists.
Pending state in a form child: useFormStatus
useFormStatus reads the status of the nearest parent <form>. It must be called from a component rendered inside that form. Calling it in the same component that renders the <form> does not work, because it reports on a parent form and finds none.
// app/SubmitButton.js
'use client';
import { useFormStatus } from 'react-dom';
export function SubmitButton({ children }) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending}>
{pending ? 'Saving…' : children}
</button>
);
}You can place this button in any form, including one in a Server Component, because the button itself is a Client Component.
// app/page.js (a Server Component)
import { createNote } from './actions';
import { SubmitButton } from './SubmitButton';
export default function Page() {
return (
<form action={createNote}>
<input name="title" required />
<SubmitButton>Add note</SubmitButton>
</form>
);
}Pending state outside forms: useTransition
When a button calls a Server Function from onClick, wrap the call in startTransition. React then keeps isPending true until the async function finishes and any resulting UI update is ready.
// 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>
);
}Without the transition, the call still runs, but React has no pending flag for you to read.
Optimistic UI: useOptimistic
An optimistic update shows the likely outcome before the server responds. useOptimistic(state, updateFn) returns the value to display and a function that adds a temporary change. When the action finishes, React discards the temporary value and shows the real state again. If the action fails, the temporary change disappears with it.
// app/NoteList.js
'use client';
import { useOptimistic } from 'react';
import { createNote } from './actions';
import { SubmitButton } from './SubmitButton';
export function NoteList({ notes }) {
const [optimisticNotes, addOptimisticNote] = useOptimistic(
notes,
(current, title) => [...current, { id: `temp-${title}`, title, sending: true }]
);
async function formAction(formData) {
const title = String(formData.get('title') ?? '').trim();
addOptimisticNote(title);
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" required />
<SubmitButton>Add note</SubmitButton>
</form>
</>
);
}Here notes arrives as a prop from a Server Component. After createNote finishes, the framework refreshes the server data, the prop changes, and the temporary note is replaced by the saved one.
The diagram shows the order of events.
Common errors
- Calling
useFormStatusin the component that renders the<form>. Move it into a child component. - Calling
addOptimisticNoteoutside an action or transition. React expects the optimistic update to run inside a form action orstartTransition. - Using a random or unstable
keyfor temporary items. Use a placeholder id that cannot collide with real ones. - Treating the optimistic value as truth. It is a guess. Keep validation and permission checks in the Server Function, as covered in the security chapter.
Exercise
A "Like" button in a Client Component calls a Server Function from onClick. Which hook gives you an isPending flag for it, and why can't you use useFormStatus here?
Show answer
Use useTransition and call the Server Function inside startTransition. useFormStatus only reports the status of a parent <form>, and this button is not submitting a form.
Exercise
What happens to an optimistic item when the Server Function throws an error?
Show answer
React discards the temporary optimistic value once the action finishes, so the list returns to the real state. The error then goes to your error handling, such as an error boundary.