Sub topic 6
Tracking results and errors with useActionState
useActionState stores the value your Action returns and exposes it to the component. This lets a form show validation messages, success notices, and server errors without hand-written useState and try/catch plumbing in the component.
This chapter assumes you know useState, controlled and uncontrolled inputs, async/await with fetch, and the browser FormData API. It also assumes you have read the earlier chapters on useTransition and on passing a function to <form action>.
The problem it solves
With a plain form action, the function runs on submit and then returns nothing useful to the component. To show an error you would add useState, call setError inside the action, and wire up pending state yourself.
useActionState combines these into one hook. It does three things:
- It calls your Action inside a transition, so React tracks the pending state.
- It saves the Action's return value as the component's state.
- It hands the previous state back to the next run of the Action.
The signature
const [state, formAction, isPending] = useActionState(action, initialState, permalink?);| Part | What it is |
|---|---|
| `action` | Your function. It receives the previous state first, then the arguments passed on dispatch. For a form, that second argument is `FormData`. |
| `initialState` | The value of `state` before the Action has ever run. It can be any serializable value. |
| `permalink` | Optional URL string. Only relevant when a form must work before JavaScript loads, which a later chapter covers. |
| `state` | The latest value returned by the Action. |
| `formAction` | A new function to pass to `<form action>`. |
| `isPending` | `true` while the Action is running. |
The action argument is the part that differs from a plain form action. A plain form action has the shape (formData) => .... An Action passed to useActionState has the shape (previousState, formData) => newState. If you forget the extra first parameter, your formData variable will hold the previous state, and formData.get will fail.
A first example
This form validates a name, posts it, and reports the outcome through state.
import { useActionState } from "react";
async function changeName(previousState, formData) {
const name = formData.get("name");
if (!name || name.trim() === "") {
return { error: "Name is required.", name: "" };
}
const response = await fetch("/api/name", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
if (!response.ok) {
return { error: "Save failed. Try again.", name };
}
return { error: null, name };
}
export function ChangeName() {
const [state, formAction, isPending] = useActionState(changeName, {
error: null,
name: "",
});
return (
<form action={formAction}>
<input name="name" defaultValue={state.name} />
<button type="submit" disabled={isPending}>
Save
</button>
{state.error && <p role="alert">{state.error}</p>}
</form>
);
}Follow one submission through the code:
- The user clicks Save. React builds a
FormDataobject from the form's named inputs. - React calls
changeName(state, formData), wherestateis the current state. On the first run that is theinitialStateobject. isPendingbecomestrue, and the button disables.- The Action returns an object. React stores it as the new
stateand setsisPendingback tofalse. - The component re-renders. If
state.erroris set, the alert paragraph appears.
Why the state is a return value
Notice that the Action never calls a setter. It reports results by returning them. This has two consequences.
First, every code path in the Action must return a value of the same shape. If one branch returns { error, name } and another returns nothing, state becomes undefined and state.error throws on the next render. Pick a shape up front and keep to it.
Second, the previous state is available as the first argument, so the Action can build on earlier results. A counter-style example makes this concrete.
import { useActionState, startTransition } from "react";
async function addToCart(previousCount, productId) {
const response = await fetch("/api/cart", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ productId }),
});
if (!response.ok) {
return previousCount;
}
return previousCount + 1;
}
export function AddToCartButton({ productId }) {
const [count, dispatch, isPending] = useActionState(addToCart, 0);
function handleClick() {
startTransition(() => {
dispatch(productId);
});
}
return (
<div>
<button onClick={handleClick} disabled={isPending}>
Add to cart
</button>
<p>Added this session: {count}</p>
</div>
);
}Two details matter here. When the request fails, the Action returns previousCount, so the state is unchanged. And because the function is called from a button click rather than a form, the dispatch is wrapped in startTransition. Without it, React warns that the Action was dispatched outside a transition and isPending will not behave correctly. A function passed to <form action> gets this wrapping automatically.
Designing the state shape
For forms, a useful state object has three parts:
errororerrors: what went wrong, ornull.values: the submitted values, so you can put them back in the inputs.successor a message: what to show when it worked.
The shape below also supports per-field errors:
import { useActionState } from "react";
async function signUp(previousState, formData) {
const email = String(formData.get("email") ?? "").trim();
const password = String(formData.get("password") ?? "");
const errors = {};
if (!email.includes("@")) {
errors.email = "Enter a valid email address.";
}
if (password.length < 8) {
errors.password = "Use at least 8 characters.";
}
if (Object.keys(errors).length > 0) {
return { errors, values: { email }, success: false };
}
try {
const response = await fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
if (!response.ok) {
return {
errors: { form: "Sign-up failed. Try again." },
values: { email },
success: false,
};
}
} catch {
return {
errors: { form: "Network error. Check your connection." },
values: { email },
success: false,
};
}
return { errors: {}, values: { email }, success: true };
}
export function SignUpForm() {
const [state, formAction, isPending] = useActionState(signUp, {
errors: {},
values: { email: "" },
success: false,
});
return (
<form action={formAction}>
<label>
Email
<input name="email" type="email" defaultValue={state.values.email} />
</label>
{state.errors.email && <p role="alert">{state.errors.email}</p>}
<label>
Password
<input name="password" type="password" />
</label>
{state.errors.password && <p role="alert">{state.errors.password}</p>}
{state.errors.form && <p role="alert">{state.errors.form}</p>}
{state.success && <p>Account created.</p>}
<button type="submit" disabled={isPending}>
{isPending ? "Creating..." : "Create account"}
</button>
</form>
);
}The password is deliberately left out of values. Never round-trip secrets through state just to refill an input.
Why `defaultValue` comes from state
React resets uncontrolled form fields after a form Action finishes. If the Action returns a validation error and you do nothing, the user's typing disappears. Reading the submitted value from state and passing it as defaultValue restores it. This works because the reset puts each field back to its defaultValue, and the new defaultValue is the value you just returned.
That is why the examples return name or values even on failure. Without it, the user must retype everything after each error.
Expected errors versus unexpected errors
Two kinds of failure need different handling.
- Expected failures are things you anticipate: empty fields, a 400 response, a duplicate email. Return them as part of the state, as shown above. The component stays mounted and shows the message.
- Unexpected failures are bugs or conditions you did not plan for. If an Action throws, React rethrows the error during rendering, so the nearest error boundary catches it. The form unmounts and the boundary's fallback appears.
Both are valid. The mistake is to let expected failures throw. A network failure while saving a form usually deserves an inline message and a chance to retry, not a replaced screen. Wrap fetch calls in try/catch when you want that, as signUp does. Note that fetch only rejects on network failure. A 500 response resolves normally, so check response.ok too.
Actions run one at a time
If a user submits again while an earlier submission is still running, React does not run the two Actions in parallel. It queues them and runs them in order. Each Action receives the state returned by the one before it. This is what keeps the "previous state" argument reliable, for example in the cart counter, where two quick clicks yield a count of 2 rather than two writes of 1.
The trade-off is latency. The second request does not start until the first finishes. Disabling the submit button with isPending, as the examples do, avoids most queueing for single forms. For work that needs true parallelism, such as uploading several files, useActionState is the wrong tool, and separate transitions or plain async code fit better.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| `formData.get is not a function` | The Action is missing the `previousState` first parameter. | Change the signature to `(previousState, formData)`. |
| `Cannot read properties of undefined` on `state` | An Action branch returned nothing. | Return a value of the same shape on every path. |
| Inputs clear after a validation error | Uncontrolled fields reset after the Action. | Return submitted values and use them as `defaultValue`. |
| Warning about dispatching outside a transition | `formAction` was called from an event handler. | Wrap the call in `startTransition`. |
| The whole form disappears on a failed save | The Action threw, and an error boundary caught it. | Catch expected errors and return them as state. |
| Passing `useActionState`'s `formAction` to a form and also calling the original action | Two code paths run the same logic. | Use only `formAction` from the hook. |
When not to use it
useActionState fits mutations whose result the UI must display. If you only need a pending flag around an async call, useTransition is smaller. If the form only needs a disabled submit button, useFormStatus in a child component is enough. If you need to keep a field's value in sync as the user types, a controlled input with useState is still the right choice, because useActionState only updates after a submission.
Exercise
A form uses useActionState(saveNote, { error: null }). The Action is async function saveNote(formData) { ... return { error: "Too short" }; }. On submit, formData.get("note") throws a TypeError. What is wrong, and how do you fix it? Also, what should the Action return in its success path so that state.error is safe to read?
Show answer
Actions passed to useActionState receive the previous state as the first argument, so formData actually holds the previous state object, which has no get method. Change the signature to async function saveNote(previousState, formData). In the success path, return an object with the same shape as the other paths, such as { error: null }. Returning nothing would make state undefined and crash state.error on the next render.
Exercise
A user submits the sign-up form with a valid email and a 5-character password. The Action returns { errors: { password: "..." }, values: { email } }, but the email field is empty after the update. Which line is missing or wrong, and why does this happen?
Show answer
The email input must use defaultValue={state.values.email}. React resets uncontrolled fields to their defaultValue after the Action finishes, so a field with no defaultValue becomes empty. The Action also has to return the submitted email in values, which it does here, so the fix is in the input's props.