Sub topic 9
When to Reach for useActionState Instead
This chapter assumes you know React function components and hooks, have read the earlier chapters on form actions and useFormStatus, and are comfortable with FormData and async functions. The examples use React 19, where useActionState is imported from react and useFormStatus is imported from react-dom.
By now you can read the pending state of a form from a child component. That covers a lot of forms, but not every one. When the form must show what the action returned, such as a validation error or a success message, useFormStatus can't help, because it reports only that a submission is running. This chapter explains what useActionState adds, how to choose between the two hooks, and how to use them together.
What each hook knows
The two hooks answer different questions.
useFormStatusanswers "Is the parent form submitting right now, and with what data?" It reads from the nearest parent<form>, so it must be called in a child component.useActionStateanswers "What did my action last return, and is it running?" It wraps one action function, and the component that calls it owns the form.
| Question | `useFormStatus` | `useActionState` |
|---|---|---|
| Imported from | `react-dom` | `react` |
| Where it is called | In a child of the `<form>` | In the component that wraps or renders the form |
| Returns | `{ pending, data, method, action }` | `[state, formAction, isPending]` |
| Knows the action's return value | No | Yes, as `state` |
| Knows the previous result | No | Yes, passed to the action as its first argument |
| Needs a child component | Yes | No |
| Works without a specific action | Yes, it reads whatever form is above it | No, it is tied to the action you pass in |
The last row matters for design. useFormStatus is generic. A SubmitButton can sit in any form and work, because it doesn't care which action runs. useActionState is specific. It is bound to one action and one piece of state.
How useActionState works
You call useActionState with an action function and an initial state:
const [state, formAction, isPending] = useActionState(action, initialState);statestarts asinitialState. After each submission it becomes whatever the action returned.formActionis a wrapped version of your action. You pass it to<form action={...}>.isPendingistruewhile the action is running.
The action you pass in gets a different signature from a plain form action. Its first argument is the previous state, and the FormData comes second:
async function action(previousState, formData) {
// return the next state
}React calls it with the previous state, so each submission can build on the last result. If you forget the extra first parameter, formData will hold the previous state and formData.get will fail. This is the most common first error with the hook.
A first example: showing a returned error
This form validates an email address. The action returns an object, and the component renders it.
'use client';
import { useActionState } from 'react';
async function subscribe(previousState, formData) {
const email = String(formData.get('email') ?? '').trim();
await new Promise((resolve) => setTimeout(resolve, 800));
if (!email.includes('@')) {
return { ok: false, email, error: 'Enter a valid email address.' };
}
return { ok: true, email, error: null };
}
const initialState = { ok: false, email: '', error: null };
export default function SubscribeForm() {
const [state, formAction, isPending] = useActionState(subscribe, initialState);
return (
<form action={formAction}>
<label htmlFor="email">Email</label>
<input
id="email"
name="email"
type="email"
defaultValue={state.email}
aria-invalid={Boolean(state.error)}
aria-describedby={state.error ? 'email-error' : undefined}
/>
<button type="submit" disabled={isPending}>
{isPending ? 'Subscribing...' : 'Subscribe'}
</button>
{state.error && (
<p id="email-error" role="alert">
{state.error}
</p>
)}
{state.ok && <p role="status">Subscribed {state.email}.</p>}
</form>
);
}Three details are worth noting.
- No child component.
isPendingcomes from the same component that renders the form, so the "hook must be in a child" rule from the earlier chapter does not apply here. - The action returns data instead of throwing. Expected failures, such as a bad email address, belong in the returned state. If an action throws, the error propagates to the nearest error boundary and replaces the form. Reserve throwing for unexpected failures.
- The action returns the submitted email. React resets uncontrolled fields in a form after its action finishes. Returning the value and using it as
defaultValuekeeps the user's input after a failed submission. Without this, the field would empty itself every time validation fails.
Using the previous state
Because the action receives previousState, it can accumulate results instead of replacing them. This example keeps a running list of messages:
'use client';
import { useActionState } from 'react';
async function addMessage(previousState, formData) {
const text = String(formData.get('text') ?? '').trim();
if (!text) {
return previousState;
}
await new Promise((resolve) => setTimeout(resolve, 500));
return [...previousState, { id: previousState.length + 1, text }];
}
export default function MessageBoard() {
const [messages, formAction, isPending] = useActionState(addMessage, []);
return (
<div>
<form action={formAction}>
<input name="text" aria-label="Message" />
<button type="submit" disabled={isPending}>
{isPending ? 'Adding...' : 'Add'}
</button>
</form>
<ul>
{messages.map((message) => (
<li key={message.id}>{message.text}</li>
))}
</ul>
</div>
);
}When the input is empty, the action returns previousState unchanged. Returning a new object each time would cause a re-render for no reason. React also runs actions from the same useActionState call one after another, so a second submission waits for the first and receives its result as previousState. That ordering is what makes the accumulation safe.
Choosing between the two hooks
Start from what the form needs to display, not from which hook looks simpler.
- Use
useFormStatusalone when the only feedback is "working on it." The form's action returns nothing the UI needs, and success is shown some other way, such as a redirect or a refreshed list. A reusableSubmitButtonis the typical case. - Use
useActionStatewhen the UI must show something the action returned: field errors, a success message, a created record's ID, or the last submitted values. - Use
useActionStatewhen you want to avoid writing a child component and the pending flag is the only thing you need from the form.isPendinggives you that directly. The trade-off is that the pending logic is now tied to this one form instead of reusable across forms. - Use both when you need the returned state and also want a shared submit button.
Combining the two hooks
The hooks do not compete. A common pattern is useActionState in the form's component for the result, plus a SubmitButton that uses useFormStatus for the pending state. The button stays reusable, and the form gets its returned state.
// SubmitButton.jsx
'use client';
import { useFormStatus } from 'react-dom';
export function SubmitButton({ children, pendingLabel = 'Working...' }) {
const { pending } = useFormStatus();
return (
<button type="submit" disabled={pending} aria-disabled={pending}>
{pending ? pendingLabel : children}
</button>
);
}
// CommentForm.jsx
'use client';
import { useActionState } from 'react';
import { SubmitButton } from './SubmitButton';
async function postComment(previousState, formData) {
const body = String(formData.get('body') ?? '').trim();
await new Promise((resolve) => setTimeout(resolve, 700));
if (body.length < 3) {
return { error: 'Comments need at least 3 characters.', body };
}
return { error: null, body: '' };
}
export default function CommentForm() {
const [state, formAction] = useActionState(postComment, { error: null, body: '' });
return (
<form action={formAction}>
<textarea name="body" defaultValue={state.body} aria-label="Comment" />
<SubmitButton pendingLabel="Posting...">Post comment</SubmitButton>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Here the third return value, isPending, is ignored. The button reads the same fact through useFormStatus. Using both for pending state in one form is redundant, so pick one source per form.
Your files can be split however your project prefers. The two components above are in one block only to keep the example compact.
useActionState with Server Actions
useActionState also works with Server Actions, and it is the usual way to show their results. The action lives in a file marked 'use server'. The component that calls useActionState is a Client Component, because hooks need client state.
// actions.js
'use server';
export async function createPost(previousState, formData) {
const title = String(formData.get('title') ?? '').trim();
if (title.length < 3) {
return { error: 'Title must be at least 3 characters.', title };
}
// Save the post to a database here.
return { error: null, title: '' };
}
// NewPostForm.jsx
'use client';
import { useActionState } from 'react';
import { createPost } from './actions';
export default function NewPostForm() {
const [state, formAction, isPending] = useActionState(createPost, {
error: null,
title: '',
});
return (
<form action={formAction}>
<input name="title" defaultValue={state.title} aria-label="Title" />
<button type="submit" disabled={isPending}>
{isPending ? 'Publishing...' : 'Publish'}
</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Two points about this setup:
- The returned state must be serializable, because it crosses the network from the server. Return plain objects, strings, numbers, and arrays. Do not return class instances or functions.
useActionStateaccepts an optional third argument, a permalink URL, for forms that should work before client JavaScript loads. When the form is submitted early, the browser posts to that URL and the server renders the resulting state. You can skip it unless your app relies on that behavior.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `formData.get is not a function` | The action was written as `(formData) => ...` but passed to `useActionState`, so the first argument is the previous state | Change the signature to `(previousState, formData)` |
| Import error for `useActionState` from `react-dom` | In older canary builds the hook was named `useFormState` and lived in `react-dom`. In React 19 it is `useActionState` in `react` | Import from `react` and upgrade React if the export is missing |
| The form is replaced by an error screen after a failed validation | The action threw the error | Return an error object for expected failures |
| Inputs empty after a failed submission | React resets uncontrolled fields after the action | Return the submitted values and use them as `defaultValue` |
| `state` is always the initial value | The form uses the original action instead of `formAction` | Pass the `formAction` returned by the hook to `<form action>` |
| Pending flag stays false in a `SubmitButton` | The button is outside the form, or the form calls `useFormStatus` itself | Render the button inside the form, in a separate component |
| Server Action returns a non-serializable value | Returned data must cross the network boundary | Return plain data only |
Trade-offs to keep in mind
useActionState couples the UI to one action's state shape. If several forms share a design, they will each need to agree on a shape such as { error, values }, or the shared components will need adapters. Settle on a small convention early, and the shared pieces stay simple.
useFormStatus stays loosely coupled, but it tells you nothing about outcomes. If you find yourself storing "did it work?" in extra useState calls alongside useFormStatus, that is a sign the form needs useActionState.
Finally, remember that the hooks report different things at different times. pending is true while the action runs, then false. state changes only when the action finishes. A form that must show both a spinner and a result uses both facts, and either hook can supply the spinner.
Exercise
A teammate wrote this action and passes it to useActionState, but formData.get('email') throws "formData.get is not a function". What is wrong, and how do you fix it? async function subscribe(formData) { const email = formData.get('email'); return { message: 'Subscribed ' + email }; }
Show answer
useActionState calls the action with the previous state as the first argument and the FormData as the second. Here formData holds the previous state, which is a plain object. Change the signature to async function subscribe(previousState, formData) and read the email from formData.
Exercise
For each form, say whether you would use useFormStatus alone, useActionState alone, or both, and why. (a) A "Delete account" button in a settings form whose action redirects the user on success. (b) A sign-up form that shows "Email already taken" under the email field. (c) A sign-up form like (b) that is part of a design system where every form button must show a spinner and a pending label.
Show answer
(a) useFormStatus alone. The UI only needs the pending state, and a redirect handles the outcome. (b) useActionState alone. The form must show an error returned by the action, and isPending covers the pending state without a child component. (c) Both. useActionState supplies the returned error state, and a shared SubmitButton uses useFormStatus so every form in the design system gets the same pending behavior.