Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 132 ยท Forms and Actions

React Hook Form with Zod

Build fast, validated React forms with React Hook Form and Zod - register, zodResolver, error display, server errors, Controller, field arrays and performance, with runnable stand-ins.

You already know how to build a form with controlled inputs: every field has a state variable, every keystroke calls a setter, and your validation runs against that state. It works, but it scales badly. A form with twenty fields means twenty state variables, twenty onChange handlers, and a component that re-renders on every key. You also write the rules in two places: once in the browser for quick feedback and once on the server for safety.

React Hook Form (RHF) and Zod are the most popular pair for solving this. React Hook Form manages the form: it tracks values, touched fields, errors and submission, mostly without re-rendering your component while the user types. Zod describes the data: a schema that says what a valid value looks like, validates it, and gives you the TypeScript type for free. A small package called a resolver connects the two.

react-hook-form, zod and @hookform/resolvers are npm packages that our editor cannot load, so real-library code on this page is read-only (React Hook Form v7 and Zod v4 style). The runnable examples use hand-written stand-ins of about fifty lines that behave like the real thing for the features shown. Install the real packages in your own project.

The shape of an RHF and Zod form

Here is a complete sign-up form with the real libraries. Read it in three layers: the schema, the hook, the markup.

JSX
// needs: npm install react-hook-form zod @hookform/resolvers
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  name: z.string().min(2, 'Enter at least 2 characters'),
  email: z.string().email('Enter a valid email'),   // Zod 4 also offers z.email()
  age: z.coerce.number().min(18, 'You must be 18 or older'),
});

function SignupForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting },
  } = useForm({
    resolver: zodResolver(schema),
    defaultValues: { name: '', email: '', age: '' },
  });

  async function onSubmit(values) {
    // values is already validated and converted: age is a number here
    await saveUser(values);
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate>
      <label>
        Name
        <input {...register('name')} />
      </label>
      {errors.name && <p role="alert">{errors.name.message}</p>}

      <label>
        Email
        <input type="email" {...register('email')} />
      </label>
      {errors.email && <p role="alert">{errors.email.message}</p>}

      <label>
        Age
        <input type="number" {...register('age')} />
      </label>
      {errors.age && <p role="alert">{errors.age.message}</p>}

      <button type="submit" disabled={isSubmitting}>Sign up</button>
    </form>
  );
}

The pieces:

  • schema is the single description of valid data. Each field has a chain of rules, and each rule can carry the message to show.
  • useForm creates the form. defaultValues provides the initial values (give one for every field, so the form's initial state is explicit and reset() knows where to go back to), and resolver tells RHF to delegate validation to Zod.
  • register('name') returns the props name, ref, onChange and onBlur. Spread onto an input, they let RHF read the value from the DOM element itself.
  • handleSubmit(onSubmit) returns the submit handler. It prevents the default submission, collects the values, runs the resolver, and calls onSubmit with the validated data only if it is valid. If it is invalid, it fills errors and focuses the first invalid field.
  • noValidate turns off the browser's own validation bubbles so that your schema is the only source of messages (see form validation for how native validation fits in).

Why it is fast: uncontrolled inputs

The key design choice is that RHF uses uncontrolled inputs. The DOM input holds its own value; RHF keeps a reference to the element and reads element.value when it needs it, mainly at submit time. Typing does not call setState, so the form component does not render while the user types.

flowchart TD
    A["User types in an input<br/>(no React state changes)"] --> B["User submits the form"]
    B --> C["handleSubmit reads every field from the DOM"]
    C --> D["Resolver runs the Zod schema"]
    D -->|"invalid"| E["Set errors, re-render once,<br/>focus the first invalid field"]
    D -->|"valid"| F["Call onSubmit with the parsed data"]

Values live in the DOM until submit. React state changes only when the errors change.

You can see this in a stand-in. The component below implements zodResolver, useForm with register and handleSubmit, and a miniature schema builder, then uses them exactly like the real code. It logs every render of the form.

A hand-written mini React Hook Form with a Zod-like schema

Type in any field and watch the console: after the first line SignupForm rendered nothing more appears, no matter how many characters you type. Press "Sign up" with the fields empty and you get one more render that shows three messages, and the cursor jumps to the name field. Fill in valid values (for example Ana, [email protected], 30) and submit: the saved data shows "age":30 as a number, even though the input produced the string "30". That conversion is the schema's job.

Schemas: one source of truth

Zod's strength is that the schema is more than a validator. It parses: it checks and also converts the input into the output type you want, and returns only the fields it knows.

  • Coercion. Every input value is a string. z.coerce.number() converts it, and fails if the result is NaN. (RHF also has register('age', { valueAsNumber: true }), which converts in the form layer instead; use one or the other.)
  • Optional values. An empty text field is '', not undefined, so an optional string often needs z.string().optional().or(z.literal('')) or a transform that maps '' to undefined.
  • Cross-field rules. A rule that compares two fields goes on the object with .refine, and path decides which field shows the message.
  • Types. In TypeScript, type SignupValues = z.infer<typeof schema> gives the form's data type, and the same schema can validate the request on your server, so the rules cannot drift apart. See TypeScript and React.

The next example shows parsing and a cross-field rule on their own, in a stand-in with the same shape as schema.safeParse(...). A schema is plain data and a function, so you can test it without any UI.

JS A schema parses, converts and compares fields

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The first call returns success: true with age converted to the number 30. The second reports both the email and the age. The third passes every single-field rule but fails the comparison, so the message lands on confirm. The last shows that a blank number counts as "not a number" rather than silently becoming 0. The cross-field rule only runs when every field passes, which is also how Zod's refine on an object behaves.

The real counterpart of the password rule is:

JSX
const schema = z
  .object({
    password: z.string().min(8),
    confirm: z.string(),
  })
  .refine((data) => data.password === data.confirm, {
    message: 'Passwords do not match',
    path: ['confirm'],
  });

Showing errors and keeping forms accessible

RHF gives you errors.fieldName.message; how you show it is up to you. Do it well:

  • Put the message next to the field and link it with aria-describedby, and mark the input with aria-invalid={errors.email ? 'true' : 'false'}. Screen readers then announce the problem when the field is focused. A shared role="alert" region can announce errors after a failed submit. See accessibility in React.
  • Make sure every input has a visible <label> (or aria-label). Placeholders are not labels.
  • RHF focuses the first invalid field after a failed submit by default (shouldFocusError). Keep that.
  • Do not disable the submit button until the form is valid; it hides why the form cannot be sent. Disable it only while isSubmitting is true to prevent double submissions.

When validation runs

By default RHF validates on submit, then re-validates on every change once a field has been submitted with an error. The mode option moves the first validation earlier:

mode First validation happens
onSubmit (default) when the user submits
onBlur when a field loses focus
onChange on every keystroke (more re-renders)
onTouched on first blur, then on every change
all on blur and on change

onTouched is a good user-friendly choice: it never scolds a user in the middle of typing their first attempt, but fixes disappear as soon as they type the correction. reValidateMode controls the behavior after the first submit.

Server errors, submit state and reset

Your schema cannot know that an email is already taken. The server tells you, and you push that message into the form with setError:

JSX
const { register, handleSubmit, setError, reset, formState: { errors, isSubmitting, isSubmitSuccessful } } =
  useForm({ resolver: zodResolver(schema) });

async function onSubmit(values) {
  const response = await fetch('/api/signup', { method: 'POST', body: JSON.stringify(values) });
  if (response.status === 409) {
    setError('email', { type: 'server', message: 'That email is already registered' });
    return;
  }
  if (!response.ok) {
    setError('root', { message: 'Something went wrong. Please try again.' });
    return;
  }
  reset(); // clear the form back to defaultValues
}

isSubmitting is true while the promise returned by onSubmit is pending, which is why it should be an async function. A server-set error is cleared when the user edits that field. Render errors.root?.message for failures that belong to the whole form. For data that must be re-validated on the server anyway (always), return field-level messages from your API in a predictable shape so you can map them to setError calls.

Controlled components, watching values and field arrays

Not every input exposes a DOM element with a .value. Custom components (a date picker, a select from a UI library, a rich-text editor) are controlled: they take value and onChange. Wrap them with Controller:

JSX
import { Controller } from 'react-hook-form';

<Controller
  name="country"
  control={control}
  render={({ field, fieldState }) => (
    <CountrySelect value={field.value} onChange={field.onChange} onBlur={field.onBlur} invalid={!!fieldState.error} />
  )}
/>

control comes from useForm(). useController is the hook version of the same thing. For library components that forward a ref to a real input, plain register often still works.

To react to a value while typing (show a live preview, enable a field when a checkbox is ticked), use watch('fieldName') or, better, useWatch({ control, name: 'fieldName' }) inside a small child component. A watch call in the root form re-renders the whole form on each change, which gives back the performance you came for. Repeating groups of fields (phone numbers, invoice lines) use useFieldArray({ control, name: 'phones' }), which provides fields, append and remove; always use field.id as the React key, not the index. Deep trees of fields can read the form with FormProvider and useFormContext instead of prop drilling (see context).

Performance habits

  • Keep typing off the render path: prefer register to Controller, and useWatch in leaf components to watch at the root.
  • formState is a proxy: RHF only re-renders for the properties you actually read. Reading formState.isDirty subscribes you to it; destructure only what you need.
  • Use mode: 'onSubmit' or onTouched unless you truly need per-keystroke validation, and let Zod run just once per event.
  • Put heavy sub-forms in their own components with memo when they are driven by useFormContext.

RHF or React 19 form actions?

React 19's form actions, useActionState and useFormStatus cover simple forms with almost no code, and they work with server functions. React Hook Form still wins when you need rich client-side behavior: many fields, field arrays, conditional fields, instant per-field feedback, or complex controlled widgets. The two combine: call handleSubmit for validation and then run your action. For a form with three fields that just posts data, you may need neither library.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does a React Hook Form form re-render so little while the user types?

    register attaches a ref to the DOM input. The input keeps its own value and no React state changes per keystroke, so the component does not render.
  2. 2. What does the resolver do?

    zodResolver runs your Zod schema on the form values and converts the issues to the error shape RHF expects.
  3. 3. The age input produces the string "30". Which Zod construct yields the number 30 in the validated data?

    Form fields always yield strings. z.coerce.number() converts and then validates, so onSubmit receives a real number.
  4. 4. The server answers that an email is already registered. How do you show this on the email field?

    Only the server knows the email is taken, so you add the error manually with setError after the request.
  5. 5. Which is the best way to show a live preview of a field's value without re-rendering the entire form on each keystroke?

    useWatch subscribes only the component that calls it, so the rest of the form stays still.

Summary

  • React Hook Form manages form state and submission with uncontrolled inputs; Zod describes valid data; a resolver such as zodResolver connects them.
  • register('name') wires an input, handleSubmit(fn) validates and calls fn only with valid, parsed data, and formState.errors holds the messages.
  • A schema parses as well as validates: it coerces strings to numbers, rejects bad values, supports cross-field rules with refine and gives you the TypeScript type with z.infer.
  • Use mode: 'onTouched' for friendly validation timing, setError for server errors and reset after success.
  • Wrap controlled UI components in Controller, use useWatch in leaf components, useFieldArray for repeating groups and field.id for keys.
  • Show errors accessibly with labels, aria-invalid and aria-describedby. For simple forms, React 19 form actions may be all you need.

Next: Fetching Data