Lesson 30 of 37React at scale
Forms at Scale: React Hook Form and Zod
Build large forms that stay fast and accessible: React Hook Form registration, one Zod schema for client and server, server errors in fields, wizards and dirty state.
The forms in your first React projects had four fields. The forms you will meet at work have forty: an insurance application, a job posting with repeating sections, a checkout with addresses, a settings page where half the fields depend on the other half. Written with one useState per field, those forms lag on every keystroke, duplicate their validation rules between client and server, lose server errors in a generic toast, and are hard to use with a screen reader. This lesson is about the patterns teams use to build big forms well: React Hook Form for state, Zod for one shared schema, and an accessibility checklist that turns "it works for me" into "it works for everyone".
Why big controlled forms get slow
In Forms you learned the controlled pattern: the value lives in state and every keystroke calls setState. That is great for a search box. In a big form the state usually lives at the top, in one object, so every keystroke re-renders the whole form: every field, every label, every derived value and every validation check. Type into field 1 below and watch the render counters in controlled mode, then switch modes.
Typing five letters into one controlled field re-renders all ten fields five times. Multiply by forty fields, a few custom inputs, and validation that runs on each render, and you get visible input lag on a mid-range phone. In uncontrolled mode the browser keeps the values, so typing renders nothing. Submitting renders once, to show the result.
Two honest notes. memo on each field, or the React Compiler from Performance, cuts the cost of the children a lot. But the form root still re-renders per keystroke, and anything computed there runs again. And re-rendering is not always a problem: measure before you rebuild a form for speed. The bigger wins of a form library are structure and correctness, not only speed.
React Hook Form: registration instead of state
React Hook Form (RHF, v7 is the current stable major) takes the uncontrolled side. register("email") returns name, ref, onChange and onBlur for a native input. RHF keeps values in its own store, reads the DOM through the ref, and only re-renders when something you subscribed to changes, such as the errors for a field.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { signupSchema, type SignupInput } from "./schema";
export function SignupForm({ onSignup }: { onSignup: (v: SignupInput) => Promise<void> }) {
const {
register,
handleSubmit,
formState: { errors, isSubmitting },
} = useForm<SignupInput>({
resolver: zodResolver(signupSchema),
defaultValues: { name: "", email: "", password: "", confirm: "" },
mode: "onTouched", // validate a field after the user leaves it, then on every change
});
return (
<form onSubmit={handleSubmit(onSignup)} noValidate>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
autoComplete="email"
{...register("email")}
aria-invalid={errors.email ? true : undefined}
aria-describedby={errors.email ? "email-error" : undefined}
/>
{errors.email && <p id="email-error">{errors.email.message}</p>}
{/* name, password and confirm follow the same pattern */}
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Creating account..." : "Create account"}
</button>
</form>
);
}The pieces you will use daily:
handleSubmit(onValid, onInvalid?)runs validation, then callsonValidwith typed values. IfonValidreturns a promise,isSubmittingstays true until it settles.formStateholdserrors,isSubmitting,isDirty,dirtyFields,touchedFields,isValidand more. It is a Proxy: RHF tracks which properties you read and only re-renders for those. So destructure what you need at the top of the component. ReadingformState.isValidsubscribes you to validity changes, which means extra validation work, so only read it if you use it.modechooses when validation runs:onSubmit(the default),onBlur,onChange,onTouchedorall.onTouchedis a good default for user-friendly forms: no red text while someone is still typing their first attempt.watchvsuseWatch:watch("plan")at the top re-renders the whole form wheneverplanchanges.useWatch({ control, name: "plan" })in a small child component re-renders only that child. Put dependent UI in a child.reset(values)sets new default values. Call it after loading saved data and after a successful save, soisDirtymeans "differs from what is saved".
Custom inputs with Controller
register needs a native input that takes a ref. A date picker, a combobox or a rich text editor from a component library usually exposes value and onChange instead. Controller (or the useController hook) bridges the two by giving you a field object to wire up.
<Controller
control={control}
name="startDate"
render={({ field, fieldState }) => (
<DatePicker
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
inputRef={field.ref} // lets RHF focus this field when it has an error
aria-invalid={fieldState.invalid || undefined}
/>
)}
/>Forget field.ref and validation still works, but focus-on-error silently skips this field. Forget field.onBlur and onTouched mode never marks it touched.
Repeating sections with useFieldArray
Invoice line items, extra phone numbers, "add another guest". useFieldArray manages the list and gives each row a stable generated id.
const { fields, append, remove } = useFieldArray({ control, name: "lineItems" });
return (
<fieldset>
<legend>Line items</legend>
{fields.map((field, index) => (
<div key={field.id}>
<label htmlFor={`item-${field.id}`}>Description</label>
<input id={`item-${field.id}`} {...register(`lineItems.${index}.description`)} />
<input type="number" aria-label="Quantity" {...register(`lineItems.${index}.quantity`, { valueAsNumber: true })} />
<button type="button" onClick={() => remove(index)}>Remove line {index + 1}</button>
</div>
))}
<button type="button" onClick={() => append({ description: "", quantity: 1 })}>Add line</button>
</fieldset>
);Use field.id as the key, never the index. As Lists and Keys showed, index keys attach the wrong DOM node to the wrong data after a removal, and with uncontrolled inputs that means the wrong text in the wrong row. Note type="button" on the helper buttons: a <button> inside a form defaults to type="submit", a classic bug where "Add line" submits the form.
fields.map((field, index) => <Row key={index} ... />) with registered inputs. The user removes row 2 of 4. What do they most likely see?One schema for client and server
Validation rules written twice drift apart. The frontend says passwords need 8 characters, the backend says 12, and users get a confusing server error after the form said everything was fine. Zod (v4 is current) fixes this by making the schema a value you import in both places, with the TypeScript type derived from it.
import { z } from "zod";
export const signupSchema = z
.object({
name: z.string().trim().min(1, "Enter your name"),
email: z.email("Enter an email address like name@example.com"),
password: z.string().min(12, "Use at least 12 characters"),
confirm: z.string(),
})
.refine((v) => v.password === v.confirm, {
message: "Passwords do not match",
path: ["confirm"], // attach the error to the confirm field, not the whole form
});
export type SignupInput = z.infer<typeof signupSchema>;On the client, zodResolver(signupSchema) runs it for RHF. On the server, you run it again, because client validation is a convenience and the server is the security boundary. A Server Action or API route is a public endpoint, so its input is unknown until parsed. Some rules can only be checked on the server ("this email is already registered"), and those errors need to land on the right field too.
"use server";
import { z } from "zod";
import { signupSchema, type SignupInput } from "@/features/signup/schema";
export type SignupResult =
| { ok: true }
| { ok: false; fieldErrors: Partial<Record<keyof SignupInput, string[]>>; formError?: string };
export async function signup(input: unknown): Promise<SignupResult> {
const parsed = signupSchema.safeParse(input);
if (!parsed.success) {
return { ok: false, fieldErrors: z.flattenError(parsed.error).fieldErrors };
}
if (await users.emailExists(parsed.data.email)) {
return { ok: false, fieldErrors: { email: ["An account with this email already exists"] } };
}
await users.create(parsed.data);
return { ok: true };
}async function onSubmit(values: SignupInput) {
const result = await signup(values);
if (result.ok) return router.push("/welcome");
for (const [field, messages] of Object.entries(result.fieldErrors)) {
setError(field as keyof SignupInput, { type: "server", message: messages?.[0] }, { shouldFocus: true });
}
if (result.formError) setError("root.server", { message: result.formError });
}
// Render errors.root?.server?.message near the submit button for errors that belong to no field.The rules live in one module. Both sides import it, and the TypeScript type comes from it, so the types cannot drift either.
When the input type and output type differ
A schema can transform data: z.coerce.number() turns "42" into 42, .trim() strips spaces, .default() fills gaps. Then the type the form holds (input) differs from the type you get after validation (output). Zod exposes both, as z.input<typeof schema> and z.output<typeof schema>, and useForm takes them as its first and third type parameters. Recent versions of @hookform/resolvers infer these from the resolver if you do not pass the generic yourself. If you see a type error mentioning unknown after adding z.coerce, this is why. Check the resolvers README for the version you have installed, because these types changed with Zod 4 support.
For number inputs you can also skip coercion and use register("age", { valueAsNumber: true }), which hands Zod a number (or NaN for an empty field, which z.number() rejects).
A server receives a form post and converts it with Object.fromEntries. The form had a number input, two checkboxes named tags (both ticked), and an unticked newsletter checkbox. What prints?
const fd = new FormData();
fd.append("age", "42");
fd.append("tags", "react");
fd.append("tags", "zod");
// the unticked newsletter checkbox sends nothing
const values = Object.fromEntries(fd);
console.log(typeof values.age, values.tags, "newsletter" in values);Accessible errors
A form that shows red text is not necessarily accessible. A screen reader user needs to know a field is invalid, hear why, and be taken to the problem. The checklist:
- Every input has a real
<label>linked byhtmlForandid. A placeholder is not a label: it disappears as soon as someone types. aria-invalidon a field with an error, so assistive tech announces it as invalid.aria-describedbypointing at the error message'sid, so the message is read when the field gets focus. Join several ids with spaces if there is hint text too.- Move focus on a failed submit. Either to the first invalid field (RHF does this by default, through
shouldFocusError, for every field whose ref it has) or, on long forms, to an error summary at the top that lists every problem as a link to its field. - Do not disable the submit button until the form is valid. A disabled button cannot be focused, gives no reason, and leaves users stuck. Let them submit and then show what is wrong.
- Use
noValidateon the form if you show your own messages, so the browser's tooltips do not compete with yours. Keeptype="email",autoCompleteandrequiredfor keyboards, password managers and autofill.
Try it below. Submit the empty form: focus jumps to the summary, and each link moves focus to its field. Then try taken@example.com to see a server-only error land on the email field. The validation function is hand-written in the shape of a Zod safeParse result, because only React is available in this sandbox.
flushSync forces React to commit the state update synchronously, so the summary element exists before you call focus(). That is one of the few places where it is the right tool. The summary has tabIndex={-1} so it can take focus from script without joining the tab order. Moving focus to it reads its heading and list, so there is no need for role="alert" as well, which would announce the same content twice.
Wizards, dirty state and unsaved changes
Long forms are often split into steps. The easy mistake is one useForm per step, which scatters the data and makes the final submit a merge job. Use one form for the whole wizard, render one step's fields at a time, and validate just that step's fields before moving on:
const STEPS: { title: string; fields: (keyof OnboardingInput)[] }[] = [
{ title: "Account", fields: ["email", "password"] },
{ title: "Company", fields: ["companyName", "size"] },
{ title: "Billing", fields: ["plan", "vatNumber"] },
];
async function next() {
const ok = await trigger(STEPS[step].fields, { shouldFocus: true });
if (ok) setStep(step + 1);
}By default RHF keeps values when a field unmounts (shouldUnregister is false), so stepping back shows what the user typed. The final handleSubmit validates everything against the full schema. For very long flows, save a draft to the server per step: users close tabs, and a ten-minute form lost to a refresh is a support ticket.
Dirty tracking compares current values to defaultValues, which is one more reason to always pass them. isDirty is true when anything differs; dirtyFields tells you which fields, useful for sending a PATCH with only changed fields. After a successful save, reset(savedValues) makes the form clean again.
Unsaved changes need two guards. Closing the tab or reloading is caught by beforeunload:
useEffect(() => {
if (!isDirty) return;
const onBeforeUnload = (e: BeforeUnloadEvent) => e.preventDefault(); // browser shows its own message
window.addEventListener("beforeunload", onBeforeUnload);
return () => window.removeEventListener("beforeunload", onBeforeUnload);
}, [isDirty]);Browsers ignore any custom text and show a generic prompt. In-app navigation does not fire beforeunload at all, because the page never unloads. That needs your router's blocking API, which you will see in Client-Side Routing.
Match each React Hook Form tool to the job it does.
When native forms and Actions are enough
Not every form needs a library. In Actions and Optimistic UI you built forms with <form action>, useActionState and useFormStatus. With a Server Action and server-side Zod validation, that stack gives you pending state, returned field errors and progressive enhancement (the form works before JavaScript loads) with no form library at all. It is the better fit for login, sign-up, newsletter, comment and search forms: few fields, validation that mostly happens on the server, and nothing dynamic.
Reach for React Hook Form when the form itself is complex: many fields, repeating sections, fields that depend on each other, instant per-field validation, wizards, or several custom inputs. Some teams also look at TanStack Form, or at Conform, which is built around Server Actions and progressive enhancement. Whatever you pick, the schema and the accessibility checklist stay the same, and those are what reviewers check.
Order what happens when a user submits a React Hook Form form with a Zod resolver, and the email is already taken.
- Tap the steps below in the right order.
- React Hook Form
- A form library that registers mostly uncontrolled inputs and re-renders only for the form state you read.
- register
- RHF function returning name, ref, onChange and onBlur to spread onto a native input.
- Controller
- RHF adapter that connects a value/onChange component, such as a date picker, to the form.
- resolver
- A function RHF calls to validate all values with a schema library.
zodResolveradapts a Zod schema. - safeParse
- Zod method that returns
{ success, data }or{ success, error }instead of throwing. - error summary
- A list of all form errors at the top, linked to each field, that takes focus after a failed submit.
- dirty state
- Whether the current values differ from the default values. Drives unsaved-changes warnings and partial updates.