Sub topic 6
Tracking results and errors with useActionState
This chapter assumes you know React function components, useState, async functions, fetch, and the browser FormData API. It also assumes you have seen a function passed to a form's action prop.
The problem it solves
A form Action runs, then something has to remember what happened. You could keep that result in useState and a separate error flag. That works, but the wiring grows with every field.
useActionState removes that wiring. It wraps an Action and stores the value the Action returns. It also gives you a ready-made form action and a pending flag.
The shape of the hook
const [state, formAction, isPending] = useActionState(action, initialState);actionis your function. It receives the previous state first and theFormDatasecond.initialStateis the value ofstatebefore the form is ever submitted.stateis whatever the last run ofactionreturned.formActionis the function you pass to<form action>.isPendingistruewhile the Action is running.
The signature differs from a plain form action. A plain form action receives only formData. An Action wrapped by useActionState receives previousState first. Forgetting this is the most common mistake: formData.get then fails because formData is actually the old state.
A worked example
This form validates a name, posts it, and reports the outcome.
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 submits. React calls
changeNamewith the initial state and the form'sFormData. isPendingbecomestrue, so the button is disabled.- The function returns an object. React stores it as the new
state. - The component renders again.
state.erroris eithernullor a message.
Returning errors instead of throwing them
Notice that changeName returns { error: ... } for expected problems. Empty input and a failed response are normal outcomes, so they are modeled as state. This keeps the error message next to the form and lets the user fix the input.
Reserve throw for unexpected failures. A thrown error is not stored in state. It propagates to the nearest error boundary, which replaces part of the UI. That is the right place for a crashed request, but a poor place for "Name is required."
Using state to keep user input
Both returns in the failure branches include name. The input reads defaultValue={state.name}, so the value comes back after a failed save. This matters because React resets uncontrolled fields in a form after its Action finishes. Returning the submitted values from the Action is how you restore them.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `formData.get is not a function` | The Action's first parameter is the previous state | Declare `(previousState, formData)` |
| Error message never appears | The Action returns nothing on failure, so `state` becomes `undefined` | Return an object in every branch |
| `Cannot read properties of undefined` on `state.error` | Same cause as above | Return a consistent shape from every branch |
| Typed text disappears after a failed submit | The form reset and the Action did not return the values | Return the values and use `defaultValue` |
| Button never re-enables | The Action never settles | Check that every path returns or throws |
Exercises
Exercise
An Action passed to useActionState begins with async function save(formData) and calls formData.get("email"). It throws a TypeError. What is wrong, and how do you fix it?
Show answer
useActionState passes the previous state as the first argument and the FormData as the second. In this function, formData is actually the previous state. Change the signature to async function save(previousState, formData).
Exercise
Your Action sets an error only when validation fails and otherwise returns nothing. After a successful save, the component crashes on state.error. Why, and what is the fix?
Show answer
A run that returns nothing sets state to undefined, so reading state.error throws. Return an object from every branch, for example { error: null, name } on success.