Sub topic 8
Pending UI with Server Actions
This chapter shows how useFormStatus behaves when a form's action is a Server Action, a function that runs on the server. It assumes you know React function components and hooks, JSX and props, HTML forms and FormData, and async functions. It also assumes you have read the earlier chapters on form actions, the pending flag, and the rule that the hook must be called from a child of the form.
The examples use the Next.js App Router, because it is the most common place to meet Server Actions. The React parts (useFormStatus, 'use server', the action prop) are the same in any framework that supports them. The Next.js-specific parts are called out.
What a Server Action is
A Server Action is an async function marked with the 'use server' directive. You can pass it to a form's action prop like any other form action. When the form is submitted, the browser sends a request to the server, the function runs there, and React receives the result.
You can mark a whole file:
'use server';
export async function createPost(formData) {
const title = formData.get('title');
// Save the post to a database here.
}Or you can mark a single function inside a Server Component:
export default function Page() {
async function subscribe(formData) {
'use server';
const email = formData.get('email');
// Store the email on the server here.
}
return (
<form action={subscribe}>
<input name="email" type="email" required />
<button type="submit">Subscribe</button>
</form>
);
}Inline Server Actions only work in Server Components. A Client Component cannot define one. It has to import one from a file that starts with 'use server'.
A Server Action receives the FormData for the submitted form as its argument. React and the framework handle serialization and the network request for you. You never write fetch.
Why pending state matters more here
With a client-side action, the delay is whatever your async function takes. With a Server Action, the delay includes a network round trip, the server work, and the time to send updated UI back. That can be hundreds of milliseconds or several seconds. Without feedback, users click again, assume the page froze, or leave.
useFormStatus gives the button a way to show that the round trip is in progress. It does not change how the action runs. It only reports the state of the nearest parent <form>.
What happens during a submission
The sequence below shows one submission of a form whose action is a Server Action.
pending becomes true when the submission starts. It stays true until the action's promise settles and React has applied the resulting update. If the action revalidates data and the server sends back new UI, that new UI arrives with the same update that ends the pending state. The user does not see a stale page after the button re-enables.
A complete example
This example has four small files. The Server Component renders the form, the action lives in its own 'use server' file, and the button is a Client Component.
First, the action:
// app/posts/actions.js
'use server';
import { revalidatePath } from 'next/cache';
export async function createPost(formData) {
const title = String(formData.get('title') ?? '').trim();
if (!title) {
throw new Error('Title is required');
}
// Simulate a slow database write.
await new Promise((resolve) => setTimeout(resolve, 1500));
console.log('Saved post:', title);
revalidatePath('/posts');
}revalidatePath is a Next.js function. It tells the framework that the cached output for /posts is stale, so the response to this action carries a fresh render of that page.
Next, the reusable button. It must be a Client Component, because hooks such as useFormStatus only run on the client:
// app/posts/SubmitButton.jsx
'use client';
import { useFormStatus } from 'react-dom';
export default function SubmitButton({ label, pendingLabel }) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending} aria-disabled={pending}>
{pending ? pendingLabel : label}
</button>
);
}Then the form, which stays a Server Component:
// app/posts/NewPostForm.jsx
import { createPost } from './actions';
import SubmitButton from './SubmitButton';
export default function NewPostForm() {
return (
<form action={createPost}>
<input name="title" required />
<SubmitButton label="Publish" pendingLabel="Publishing..." />
</form>
);
}Finally, the page that uses it:
// app/posts/page.jsx
import NewPostForm from './NewPostForm';
export default function PostsPage() {
return (
<main>
<h1>Posts</h1>
<NewPostForm />
</main>
);
}Submit the form and the button changes to "Publishing..." for about 1.5 seconds, then returns to "Publish".
Why the split into files matters
The form has no 'use client' and no hooks, so it can stay on the server. Only SubmitButton ships JavaScript to the browser. The button is a child of the form in the rendered tree, even though it is defined in another file. That satisfies the child-component rule. What counts is where the component is rendered, not where it is defined.
| Piece | Where it runs | Why |
|---|---|---|
| `NewPostForm` | Server | It only renders markup and passes the action |
| `createPost` | Server | It is marked `'use server'` and touches data |
| `SubmitButton` | Client | It calls a hook, so it needs `'use client'` |
| `useFormStatus` | Client | It reads React's client-side form state |
Reading data and method while a Server Action runs
The hook also returns data, method, and action. With Server Actions, data is the FormData the user submitted. That lets a child show what is being sent without lifting state into the form.
// app/posts/PendingNotice.jsx
'use client';
import { useFormStatus } from 'react-dom';
export default function PendingNotice() {
const { pending, data, method } = useFormStatus();
if (!pending) return null;
return (
<p role="status">
Publishing "{data?.get('title')}" using {method}...
</p>
);
}Place <PendingNotice /> inside the form next to the button. method is the form's HTTP method, which is 'get' by default. role="status" makes it a polite live region, so screen readers announce the text when it appears.
For a Server Action, the action field is not the original function you wrote. It is a reference React uses to call the server. Do not compare it to your own function or call it yourself. Use pending and data, and treat action as informational.
Binding extra arguments
A form only sends its fields, but an action often needs more, such as the ID of the row being deleted. Use bind to pre-fill leading arguments:
// app/posts/actions.js (addition)
export async function deletePost(id, formData) {
await new Promise((resolve) => setTimeout(resolve, 800));
console.log('Deleted post', id);
revalidatePath('/posts');
}// app/posts/DeleteForm.jsx
import { deletePost } from './actions';
import SubmitButton from './SubmitButton';
export default function DeleteForm({ id }) {
const deleteWithId = deletePost.bind(null, id);
return (
<form action={deleteWithId}>
<SubmitButton label="Delete" pendingLabel="Deleting..." />
</form>
);
}The bound id becomes the first argument and FormData is passed after it. This works in a Server Component. Because the same SubmitButton is reused, you get a pending state on the delete form with no new hook code. If a page lists twenty posts, each DeleteForm has its own status, and clicking one Delete button does not disable the other nineteen. useFormStatus reads only the nearest parent form.
Before and after hydration
A form with a Server Action in a Server Component works even before the page's JavaScript has loaded. The browser falls back to a normal form submission, and the framework handles it. This is called progressive enhancement.
The pending state is different. It comes from React running in the browser, so it only works after hydration, which is when React attaches to the server-rendered HTML. If a user submits very early on a slow connection, the submission goes through, but the button never shows the pending label. The page then reloads or navigates as a full request.
Treat the pending UI as an improvement on top of a working form. Do not make the form's correctness depend on it.
Errors and the pending state
If a Server Action throws, pending returns to false when the submission ends. The error is not available to useFormStatus. The nearest error boundary handles it. In Next.js, that is the closest error.js file.
Throwing is right for unexpected failures. For expected failures such as "title is required" or "email already used", it is better to return a value and render it. The hook does not give you a returned value. That need is covered in the chapter on useActionState.
Preventing duplicate submissions
Disabling the button stops most double clicks, because a disabled button cannot be clicked. Browsers also generally refuse implicit submission, such as pressing Enter in a text field, when the form's default button is disabled. Neither is a guarantee. The user can submit from another tab, or the request can be retried by a flaky network.
Make the server side safe as well:
- Use a unique constraint, such as a unique slug or a client-generated idempotency key, so a duplicate insert fails cleanly.
- Make the action safe to run twice when you can, for example with an upsert.
- Do not rely on the disabled button as the only protection.
Accessibility notes for pending buttons
The button in this chapter sets both disabled and aria-disabled. They are not the same.
disabledremoves the button from the tab order and blocks clicks. Keyboard focus is lost if the focused button becomes disabled, which can confuse screen reader users.aria-disabled="true"only announces the state. The button stays focusable, and you must block the action yourself.
One option is to keep aria-disabled and ignore clicks while pending. The simpler option, shown here, is disabled plus a visible label change. Add a role="status" region, like PendingNotice, so the change is announced and not only shown.
Using it with a result: a preview of useActionState
If the form must show a message returned by the server, useFormStatus is not enough. useActionState runs the action and gives you its result and a pending flag in the component that owns the form:
'use client';
import { useActionState } from 'react';
async function subscribe(previousState, formData) {
await new Promise((resolve) => setTimeout(resolve, 1000));
return { message: 'Subscribed ' + formData.get('email') };
}
export default function SubscribeForm() {
const [state, formAction, isPending] = useActionState(subscribe, { message: '' });
return (
<form action={formAction}>
<input name="email" type="email" />
<button type="submit" disabled={isPending}>Subscribe</button>
<p>{state.message}</p>
</form>
);
}The two hooks work well together. A common pattern is to use useActionState in the form for results and errors, and keep a shared SubmitButton with useFormStatus for the pending state. That avoids passing isPending through props to every button.
Troubleshooting pending state with Server Actions
If the button never changes, check these in order.
- Is the button rendered inside the
<form>? The hook cannot see a form that is a sibling or a parent of its component. Call it in a child, not in the component that renders the<form>. - Does the file have
'use client'? Without it, the build fails with an error about using a hook in a Server Component. Fix it by moving the hook into its own client file. - Is
actiona function? If you wroteaction="/api/save"as a string, there is no action, andpendingis not driven by React. - Is the action actually async? A function that returns immediately finishes before the user sees a pending frame. Add a real
await, or a short delay while testing. - Has the page hydrated? Before hydration, pending state does not update. Test with a throttled network and wait for the page to finish loading.
- Did you import from the right package?
useFormStatuscomes fromreact-dom, notreact.useActionStatecomes fromreact. - Is the error swallowed? If the action throws before its first
await, the pending state may flash for only an instant. Check the server logs.
Summary
- A Server Action is an async function with
'use server', passed to a form'sactionprop. useFormStatusreportspendingfor the whole round trip, from submit until the result is applied.- The hook must run in a Client Component rendered inside the form. The form itself can stay a Server Component.
dataholds the submittedFormDatawhile pending.methodis the form's HTTP method.- Pending UI depends on hydration, so the form must work without it.
- Use
useActionStatewhen you need the action's returned value, and combine it with a sharedSubmitButtonwhen you want both.
Exercise
A teammate writes a Server Component ContactForm that renders <form action={sendMessage}> and, in the same component, calls useFormStatus() to disable the submit button. The build fails. Give two separate reasons it fails or does not work, and describe the fix.
Show answer
First, a Server Component cannot call hooks, so useFormStatus there causes a build error unless the file is a Client Component. Second, even in a Client Component, calling the hook in the component that renders the <form> does not read that form's status, so pending would always be false. The fix is to move the button into a separate file that starts with 'use client', call useFormStatus() there, and render that SubmitButton as a child inside the form. ContactForm can then remain a Server Component.
Exercise
You have a list of 20 posts, each with its own <form action={deletePost.bind(null, post.id)}> containing the same SubmitButton. A user clicks Delete on the third post. Which buttons show their pending label, and why?
Show answer
Only the third post's button. useFormStatus reads the status of the nearest parent form, and each button has a different parent form. The other 19 forms are not submitting, so their buttons stay in their normal state.
Exercise
An action throws new Error('Title is required') when the title is empty. After the user submits an empty title, what does useFormStatus report, and where does the error message go?
Show answer
pending returns to false once the submission ends, and the hook gives no access to the error. The error goes to the nearest error boundary, which in Next.js is the closest error.js. To show a message next to the form instead, return the message from the action and read it with useActionState.