Sub topic 7
Returning validation errors instead of throwing
This chapter assumes you know how useActionState is called, what an action function receives (prevState and FormData), and how to read isPending. Here you will handle invalid input as part of the state.
Why not throw?
A user who types a bad email address has not caused a bug. This is an expected outcome, so it belongs in the state your action returns.
If an action throws, React treats it as an unexpected failure. The error propagates to the nearest error boundary, which replaces the form with a fallback UI. The user loses the form and everything they typed. Throwing also gives you no easy way to show a message next to the field that caused it.
When you return an error, the component stays mounted and re-renders with the new state. The form, the input, and the message appear together.
A state shape for errors
Use a status field, an errors object keyed by field name, and the submitted values. A form key in errors can hold a message that belongs to the whole form.
import { useActionState } from "react";
function validate(values) {
const errors = {};
if (!values.name) errors.name = "Name is required.";
if (!values.email.includes("@")) errors.email = "Enter a valid email address.";
return errors;
}
async function signUp(prevState, formData) {
const values = {
name: String(formData.get("name") ?? "").trim(),
email: String(formData.get("email") ?? "").trim(),
};
const errors = validate(values);
if (Object.keys(errors).length > 0) {
return { status: "error", errors, values };
}
const response = await fetch("/api/signup", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
if (!response.ok) {
return {
status: "error",
errors: { form: "Sign-up failed. Please try again." },
values,
};
}
return { status: "success", errors: {}, values: { name: "", email: "" } };
}
export function SignUpForm() {
const [state, formAction, isPending] = useActionState(signUp, {
status: "idle",
errors: {},
values: { name: "", email: "" },
});
return (
<form action={formAction}>
<label>
Name
<input
name="name"
type="text"
defaultValue={state.values.name}
aria-invalid={Boolean(state.errors.name)}
/>
</label>
{state.errors.name && <p role="alert">{state.errors.name}</p>}
<label>
Email
<input
name="email"
type="text"
defaultValue={state.values.email}
aria-invalid={Boolean(state.errors.email)}
/>
</label>
{state.errors.email && <p role="alert">{state.errors.email}</p>}
<button type="submit" disabled={isPending}>
{isPending ? "Signing up..." : "Sign up"}
</button>
{state.errors.form && <p role="alert">{state.errors.form}</p>}
{state.status === "success" && <p>Welcome aboard.</p>}
</form>
);
}Each branch returns the same shape, so the component never needs to check whether errors or values exist. Returning values lets the inputs show what the user typed. The next chapter explains why that matters when React resets the form.
Network failures are not exceptions
fetch only rejects on network-level problems. A 400 or 500 response still resolves normally. Check response.ok and turn failures the user can act on into state, as the example does. Server-side validation messages usually arrive this way.
Let the action throw for conditions the user cannot fix and you did not expect, such as a malformed response or a bug. An error boundary is the right place for those.
Common mistakes
- Returning
undefinedon one branch. The next render then fails onstate.errors. - Validating only in the browser. Client checks help users, but the action (or the server behind it) must check again.
- Never clearing old errors. A successful submission should return
errors: {}, or the old messages remain.
Exercise
A submission fails because the email is invalid. Why is returning { errors: { email: "..." }, values } better than throwing an Error?
Show answer
A thrown error goes to the nearest error boundary, which replaces the form and loses the user's input. Returned state keeps the form mounted. It also lets you show the message beside the field and refill the inputs from values. Throwing is for unexpected failures only.