Sub topic 14
Common pitfalls and error handling
This chapter assumes you can write a useActionState form and know the basics from earlier chapters: the action receives (previousState, formData), the hook returns [state, formAction, isPending], and React resets uncontrolled fields after an action finishes. Here you will learn the mistakes that most often break such forms and how to handle failures deliberately.
Two kinds of failure
An action can fail in two ways, and each needs its own handling.
- Expected failures are part of normal use: an empty field, an email that is already registered, a server that answers with a 4xx status. Return these as state and render them next to the form.
- Unexpected failures are bugs or outages you cannot recover from inside the form: a thrown exception, a rejected promise you did not catch. Let these throw so the nearest error boundary can show a fallback.
Pitfall 1: Treating the action like a plain submit handler
The action passed to useActionState receives the previous state first. The most common mistake is writing it as if formData were the first argument.
// Wrong: formData is actually the previous state here
async function subscribe(formData) {
const email = formData.get("email"); // TypeError
}
// Right
async function subscribe(prevState, formData) {
const email = String(formData.get("email") ?? "");
return { ...prevState, email };
}The reverse mistake also happens. If you pass a function with the (formData) signature straight to <form action>, it works, but it is no longer connected to useActionState. Pick one approach per form.
Pitfall 2: Throwing for validation errors
When an action throws, React does not call your component with an error state. The error propagates to the nearest error boundary, which replaces the whole subtree, including the form. The user loses what they typed.
// Wrong for validation: the form disappears
async function subscribe(prevState, formData) {
const email = String(formData.get("email") ?? "");
if (!email.includes("@")) throw new Error("Enter a valid email address.");
// ...
}Return { error: "...", email } instead, as shown in the first chapters of this tutorial. Reserve throw for failures the form cannot sensibly handle.
Pitfall 3: Forgetting that fetch does not reject on HTTP errors
fetch only rejects when the network request itself fails. A 400 or 500 response resolves normally. If you skip the response.ok check, the action reports success when the server refused the request.
The next action handles all three outcomes: invalid input, a failed request, and success.
import { useActionState } from "react";
async function saveProfile(prevState, formData) {
const name = String(formData.get("name") ?? "").trim();
if (!name) {
return { status: "invalid", message: "Name is required.", name };
}
try {
const response = await fetch("/api/profile", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name }),
});
if (response.status === 409) {
return { status: "invalid", message: "That name is taken.", name };
}
if (!response.ok) {
return {
status: "failed",
message: "The server could not save your profile. Try again.",
name,
};
}
} catch {
return {
status: "failed",
message: "Network problem. Check your connection and try again.",
name,
};
}
return { status: "saved", message: "Profile saved.", name: "" };
}
export function ProfileForm() {
const [state, formAction, isPending] = useActionState(saveProfile, {
status: "idle",
message: null,
name: "",
});
return (
<form action={formAction}>
<input name="name" type="text" defaultValue={state.name} />
<button type="submit" disabled={isPending}>
{isPending ? "Saving..." : "Save"}
</button>
{state.status === "saved" && <p>{state.message}</p>}
{(state.status === "invalid" || state.status === "failed") && (
<p role="alert">{state.message}</p>
)}
</form>
);
}Two design choices are worth noting. A status field replaces the pair of booleans ok and error, which can drift into impossible combinations. Every returned state also includes the submitted name, so the field keeps its value after React resets the form.
Pitfall 4: Losing the user's input after a reset
React resets uncontrolled fields to their defaultValue after an action completes. If you do not feed the submitted value back through state, a failed submission clears the field. Return the value in every branch that should keep it, and clear it (as saveProfile does on success) only when the submission has succeeded.
Do not switch to value plus onChange to avoid this. A controlled input works, but you then manage the value by hand, which is the work useActionState is meant to remove.
Pitfall 5: Using useFormStatus in the wrong place
useFormStatus reads the status of the nearest parent <form>. If you call it in the same component that renders the <form>, there is no parent form, and pending is always false.
import { useFormStatus } from "react-dom";
// Wrong: this component renders the form, so pending never becomes true
function BrokenForm({ action }) {
const { pending } = useFormStatus();
return (
<form action={action}>
<button disabled={pending}>Save</button>
</form>
);
}
// Right: the button is a child of the form
function SubmitButton() {
const { pending } = useFormStatus();
return <button disabled={pending}>{pending ? "Saving..." : "Save"}</button>;
}If the component that calls useActionState also renders the form, isPending is already available, so useFormStatus is only needed for reusable child components.
Pitfall 6: Dispatching outside a form without a transition
The formAction function is designed to run inside a form's action prop, where React already wraps it in a transition. If you call the dispatcher from an onClick handler, you must wrap it yourself.
import { startTransition, useActionState } from "react";
async function increment(prevCount, amount) {
return prevCount + amount;
}
export function Counter() {
const [count, dispatch, isPending] = useActionState(increment, 0);
return (
<button
disabled={isPending}
onClick={() => startTransition(() => dispatch(1))}
>
Count: {count}
</button>
);
}Without startTransition, React warns that the action was called outside a transition, and isPending does not reflect the pending state correctly.
Pitfall 7: Assuming submissions run in parallel
useActionState queues actions. If the user submits twice while the first is still running, the second action starts only after the first returns, and it receives the first action's result as prevState. This keeps state consistent, but it has consequences:
- A slow first request delays every later submission.
- A failed first submission still hands its error state to the next action, so the second action should not assume the previous state is a success.
- Disabling the button with
isPendingis a good habit. It stops accidental double submits, and the queue is the safety net for cases where the button cannot be disabled, such as a dispatcher called from a keyboard shortcut.
If you need to cancel an earlier request, the queue will not do it for you. Use an AbortController inside your own code, or skip the work when prevState shows it is already done.
Pitfall 8: Mutating the previous state
The state you return should be a new value. Mutating prevState and returning it can leave React with nothing to compare, so the component may not update.
// Wrong: same array reference, mutated in place
async function addItem(prevItems, formData) {
prevItems.push(String(formData.get("name") ?? ""));
return prevItems;
}
// Right: new array
async function addItem(prevItems, formData) {
const name = String(formData.get("name") ?? "").trim();
if (!name) return prevItems; // unchanged, so returning it is fine
return [...prevItems, name];
}Returning prevItems untouched is fine when nothing changed. Mutating it is not.
Pitfall 9: Server functions and the permalink
When the action is a server function, three details commonly cause trouble:
- The state you return crosses the network, so it must be serializable. Return plain objects, arrays, strings, numbers, and booleans. Do not return class instances or functions.
- The optional third argument, the permalink, must point to a page that renders the same form. It only matters for progressive enhancement, where the form submits before client JavaScript loads. Your framework must support server functions for it to have any effect.
- Server code and client code live in separate files or boundaries. The
"use server"directive belongs at the top of the actions file, and the"use client"directive at the top of the component file, as in the earlier chapter.
Catching thrown errors with an error boundary
For unexpected failures, wrap the form in an error boundary. React still requires a class component for this.
import { Component } from "react";
export class FormErrorBoundary extends Component {
state = { error: null };
static getDerivedStateFromError(error) {
return { error };
}
render() {
if (this.state.error) {
return (
<div role="alert">
<p>Something went wrong. Reload the page and try again.</p>
</div>
);
}
return this.props.children;
}
}
// Usage:
// <FormErrorBoundary>
// <ProfileForm />
// </FormErrorBoundary>Place the boundary around the form, not around the whole page, so a failure in one form does not take the rest of the page down.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| `formData.get` is not a function | Action written as `(formData)` | Use `(prevState, formData)` |
| Whole form vanishes on bad input | Validation throws | Return an error in state |
| Success shown after a server error | Missing `response.ok` check | Check status, return a failure state |
| Field clears after a failed submit | Value not returned in state | Return the value, use `defaultValue` |
| Button never shows pending | `useFormStatus` in the form's own component | Move it into a child component |
| Warning about a missing transition | Dispatcher called from `onClick` | Wrap in `startTransition` |
| List does not update | `prevState` mutated | Return a new array or object |
Exercise
A signup action calls fetch("/api/signup") and then always returns { ok: true }. Users report seeing "Welcome!" even when the server answers 500. Name the two changes that fix this, and say whether the 500 case should throw or return state.
Show answer
First, check response.ok after the await. Second, wrap the call in try/catch so a network rejection is also handled. A 500 on a signup form is something the user can retry, so return a failure state such as { status: "failed", message: "..." , email } and render it in the form. Throw only if you want the error boundary to replace the form.
Exercise
You build a SaveButton that calls useFormStatus, but you put the hook in the same component that renders <form>. The button never shows "Saving...". Why, and what are two ways to fix it?
Show answer
useFormStatus reports the status of a parent form, and the component that renders the form has no parent form, so pending stays false. Fix it by moving the button into its own child component rendered inside the form, or by using the isPending value returned from useActionState in the form's component.