Sub topic 14
Common pitfalls and error handling
This chapter assumes you know useState, async functions, and the FormData API. It also assumes you have used useActionState with a form, as in the earlier chapters. Here we look at the mistakes people make most often and how to handle failures so the form stays usable.
Return expected errors, throw unexpected ones
An expected error is something the user can fix, such as an empty field or a duplicate email. Return it as part of the next state. A thrown error is different. React treats it as a rendering failure and passes it to the nearest error boundary. The form disappears, and the state you were building is lost.
Use this rule:
- Validation problems and server rejections: return them as state.
- Bugs and failures you cannot recover from locally: let them throw, and provide an error boundary.
- Network calls: wrap them in
try/catchand return a failure state, so a dropped connection does not take down the page.
A complete example
This action covers validation, a rejected response, and a network failure. Each failure path returns the typed title, so the input keeps its value after React resets the form.
import { useActionState } from "react";
async function savePost(prevState, formData) {
const title = String(formData.get("title") ?? "").trim();
if (!title) {
return { status: "invalid", message: "Title is required.", title };
}
try {
const res = await fetch("/api/posts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ title }),
});
if (!res.ok) {
return { status: "failed", message: `Server error ${res.status}. Try again.`, title };
}
} catch {
return { status: "failed", message: "Network error. Check your connection.", title };
}
return { status: "saved", message: "Post saved.", title: "" };
}
export function PostForm() {
const [state, formAction, isPending] = useActionState(savePost, {
status: "idle",
message: null,
title: "",
});
return (
<form action={formAction}>
<input name="title" type="text" defaultValue={state.title} />
<button type="submit" disabled={isPending}>
{isPending ? "Saving..." : "Save"}
</button>
{state.message && (
<p role={state.status === "saved" ? "status" : "alert"}>{state.message}</p>
)}
</form>
);
}Pitfalls to check first
- Missing the first argument. The action receives
prevStatefirst andformDatasecond. If you writeasync function action(formData), the "form data" is actually your previous state, andformData.getis not a function. - Forgetting to return. Every code path must return the next state. A path that returns nothing sets the state to
undefined, andstate.errorthen throws during render. - Mutating the previous state. Build a new object or array, as in
[...prevItems, name]. MutatingprevStateand returning it can skip updates. - Losing typed values. React resets an uncontrolled form after the action finishes. Return the submitted values in state and use
defaultValue. - Dispatching outside a form without a transition. Calling the dispatcher from
onClickneedsstartTransition. Without it, React warns andisPendingdoes not behave as expected. - Calling
useFormStatusin the wrong place. It reads the status of a parent<form>. If you call it in the same component that renders the form,pendingis alwaysfalse. Move the call into a child component such as aSubmitButton. - Assuming submissions overlap. Repeated submissions are queued and run one after another. Each action sees the state the previous one returned. Disabling the button with
isPendingis still good practice, but your logic does not need to guard against two actions running at once.
Exercise
Exercise
Your action calls fetch, and a user goes offline. The page goes blank, and a nearby error boundary shows its fallback. What caused this, and how do you fix it so the form stays visible with a message?
Show answer
The rejected fetch promise made the action throw, and React sent the error to the error boundary. Wrap the call in try/catch. In the catch block, return a failure state such as { status: "failed", message: "Network error. Check your connection.", title }. The component then renders state.message and the form stays on screen with the typed value kept.