Skip to content

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.

15 min read0/4 questions

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.

ReactRenderCost.tsx
import { useRef, useState } from "react";import type { FormEvent } from "react"; const FIELDS = Array.from({ length: 10 }, (_, i) => `Field ${i + 1}`); // Demo only: writing a ref during render is not something to do in real code.function useRenderCount() { const count = useRef(0); count.current += 1; return count.current;} function ControlledField({ name, value, onChange }: { name: string; value: string; onChange: (name: string, v: string) => void }) { const renders = useRenderCount(); return ( <label style={{ display: "flex", gap: 8, alignItems: "center" }}> <span style={{ width: 70 }}>{name}</span> <input aria-label={name} value={value} onChange={(e) => onChange(name, e.target.value)} /> <small>renders: {renders}</small> </label> );} function UncontrolledField({ name }: { name: string }) { const renders = useRenderCount(); return ( <label style={{ display: "flex", gap: 8, alignItems: "center" }}> <span style={{ width: 70 }}>{name}</span> <input aria-label={name} name={name} defaultValue="" /> <small>renders: {renders}</small> </label> );} function ControlledForm() { const [values, setValues] = useState<Record<string, string>>({}); const update = (name: string, v: string) => setValues({ ...values, [name]: v }); return ( <div style={{ display: "grid", gap: 4 }}> {FIELDS.map((f) => <ControlledField key={f} name={f} value={values[f] ?? ""} onChange={update} />)} </div> );} function UncontrolledForm() { const [filled, setFilled] = useState<number | null>(null); function handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const data = new FormData(e.currentTarget); setFilled([...data.values()].filter((v) => String(v).trim()).length); } return ( <form onSubmit={handleSubmit} style={{ display: "grid", gap: 4 }}> {FIELDS.map((f) => <UncontrolledField key={f} name={f} />)} <button type="submit">Submit</button> {filled !== null && <p>Read {filled} filled fields from the DOM, on submit only.</p>} </form> );} export default function App() { const [mode, setMode] = useState<"controlled" | "uncontrolled">("controlled"); return ( <div> <button onClick={() => setMode(mode === "controlled" ? "uncontrolled" : "controlled")}> Switch to {mode === "controlled" ? "uncontrolled" : "controlled"} </button> <p>Mode: <strong>{mode}</strong></p> {mode === "controlled" ? <ControlledForm /> : <UncontrolledForm />} </div> );}

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.

features/signup/SignupForm.tsx
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 calls onValid with typed values. If onValid returns a promise, isSubmitting stays true until it settles.
  • formState holds errors, isSubmitting, isDirty, dirtyFields, touchedFields, isValid and 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. Reading formState.isValid subscribes you to validity changes, which means extra validation work, so only read it if you use it.
  • mode chooses when validation runs: onSubmit (the default), onBlur, onChange, onTouched or all. onTouched is a good default for user-friendly forms: no red text while someone is still typing their first attempt.
  • watch vs useWatch: watch("plan") at the top re-renders the whole form whenever plan changes. 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, so isDirty means "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.

features/booking/StartDateField.tsx
<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.

features/invoice/LineItems.tsx
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.

Quick check
A form renders fields.map((field, index) => <Row key={index} ... />) with registered inputs. The user removes row 2 of 4. What do they most likely see?
Need a nudge? A hint rules out a wrong answer.

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.

features/signup/schema.ts
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.

app/signup/actions.ts
"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 };
}
features/signup/SignupForm.tsx (submit handler)
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.
One schema, validated in two places
schema.ts: Zod schema + inferred typeschema.tsZod schema + inferred typeSignup form: RHF + zodResolverSignup formRHF + zodResolverServer Action: safeParse(input: unknown)Server ActionsafeParse(input: unknown)Users table: unique emailUsers tableunique emailimportimportsubmit valuesemail taken?fieldErrors

The rules live in one module. Both sides import it, and the TypeScript type comes from it, so the types cannot drift either.

1/5
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).

Predict the outputJavaScript

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);
Need a nudge? Hints walk you through it.

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 by htmlFor and id. A placeholder is not a label: it disappears as soon as someone types.
  • aria-invalid on a field with an error, so assistive tech announces it as invalid.
  • aria-describedby pointing at the error message's id, 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 noValidate on the form if you show your own messages, so the browser's tooltips do not compete with yours. Keep type="email", autoComplete and required for 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.

ReactAccessibleErrors.tsx
import { useRef, useState } from "react";import { flushSync } from "react-dom";import type { FormEvent } from "react"; type Values = { name: string; email: string; password: string };type Field = keyof Values;type FieldErrors = Partial<Record<Field, string>>; const LABELS: Record<Field, string> = { name: "Full name", email: "Email", password: "Password" };const FIELDS = Object.keys(LABELS) as Field[]; // Same shape as Zod's safeParse result.function validate(v: Values): { success: true; data: Values } | { success: false; errors: FieldErrors } { const errors: FieldErrors = {}; if (!v.name.trim()) errors.name = "Enter your name"; if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email)) errors.email = "Enter an email address like name@example.com"; if (v.password.length < 12) errors.password = "Use at least 12 characters"; return Object.keys(errors).length ? { success: false, errors } : { success: true, data: v };} // The "server" runs the same rules, plus one only it can check.async function serverSignup(v: Values): Promise<{ ok: true } | { ok: false; errors: FieldErrors }> { await new Promise((r) => setTimeout(r, 600)); const parsed = validate(v); if (!parsed.success) return { ok: false, errors: parsed.errors }; if (v.email.toLowerCase() === "taken@example.com") { return { ok: false, errors: { email: "An account with this email already exists" } }; } return { ok: true };} export default function App() { const [errors, setErrors] = useState<FieldErrors>({}); const [status, setStatus] = useState<"idle" | "submitting" | "done">("idle"); const summaryRef = useRef<HTMLDivElement>(null); function showErrors(next: FieldErrors) { flushSync(() => setErrors(next)); // commit now so the summary exists summaryRef.current?.focus(); } async function handleSubmit(e: FormEvent<HTMLFormElement>) { e.preventDefault(); const data = new FormData(e.currentTarget); const values: Values = { name: String(data.get("name") ?? ""), email: String(data.get("email") ?? ""), password: String(data.get("password") ?? ""), }; const parsed = validate(values); if (!parsed.success) return showErrors(parsed.errors); setStatus("submitting"); const result = await serverSignup(values); setStatus(result.ok ? "done" : "idle"); if (!result.ok) showErrors(result.errors); } if (status === "done") return <p role="status">Account created. Check your inbox.</p>; const problems = FIELDS.filter((f) => errors[f]); return ( <form onSubmit={handleSubmit} noValidate style={{ display: "grid", gap: 10, maxWidth: 360 }}> {problems.length > 0 && ( <div ref={summaryRef} tabIndex={-1} aria-labelledby="summary-title" style={{ border: "2px solid crimson", padding: 10 }}> <strong id="summary-title"> {problems.length === 1 ? "There is 1 problem" : `There are ${problems.length} problems`} </strong> <ul style={{ margin: "6px 0 0", paddingLeft: 18 }}> {problems.map((f) => ( <li key={f}> <a href={`#${f}`} onClick={(e) => { e.preventDefault(); document.getElementById(f)?.focus(); }}> {LABELS[f]}: {errors[f]} </a> </li> ))} </ul> </div> )} {FIELDS.map((f) => ( <div key={f} style={{ display: "grid", gap: 2 }}> <label htmlFor={f}>{LABELS[f]}</label> <input id={f} name={f} type={f === "password" ? "password" : f === "email" ? "email" : "text"} autoComplete={f === "password" ? "new-password" : f} aria-invalid={errors[f] ? true : undefined} aria-describedby={errors[f] ? `${f}-error` : undefined} /> {errors[f] && <small id={`${f}-error`} style={{ color: "crimson" }}>{errors[f]}</small>} </div> ))} <button type="submit" disabled={status === "submitting"}> {status === "submitting" ? "Creating account..." : "Create account"} </button> </form> );}

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:

features/onboarding/Wizard.tsx
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:

features/settings/useUnsavedChangesWarning.ts
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 the pairs0/6 matched

Match each React Hook Form tool to the job it does.

Choose an item, then its match on the other side.

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.

Put it in order6 steps

Order what happens when a user submits a React Hook Form form with a Zod resolver, and the email is already taken.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
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. zodResolver adapts 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.