SkillPilotAI

React Hook Form + Zod

Forms with a useState for every input get messy and re-render on every keystroke. React Hook Form keeps inputs uncontrolled and fast, and Zod keeps all validation rules in one schema that can be reused on the server.

53.1 Problem: a manual form

  • One email field already needs two states (email, error) and a handler that validates by hand.
  • Typing rahul re-renders the component on every letter, and Invalid email shows from the very first letter.
React (JSX)
function Signup() {  const [email, setEmail] = useState("");  const [error, setError] = useState("");  console.log("render");   const update = (e) => {    setEmail(e.target.value);    setError(e.target.value.includes("@")      ? "" : "Invalid email");  };  return <>    <input value={email} onChange={update} />    <p>{error}</p>  </>;}
Output
[ rahul ]Invalid emailConsole: render, render, render, render, render, render

53.2 Why is it used?

  • Two states + a handler per field: with ten fields the code gets messy fast.
  • The whole form re-renders on every keystroke, which feels slow in big forms.
  • Validation rules are scattered inside handlers.
  • React Hook Form keeps inputs uncontrolled and reads values from the DOM (refs); Zod keeps all rules in one place called a schema.

53.3 React Hook Form: register and handleSubmit

  • useForm() gives register and handleSubmit.
  • {...register("email")} connects the input's name, onChange and ref to the form.
  • handleSubmit calls preventDefault for you and passes all values to onSubmit as one object.
  • Typing causes no new render after page load; submit prints the whole data object.
React (JSX)
import { useForm } from "react-hook-form"; function Signup() {  const { register, handleSubmit } = useForm();  console.log("render");  const onSubmit = (d) => console.log(d);   return (    <form onSubmit={handleSubmit(onSubmit)}>      <input {...register("email")} />      <input {...register("password")} />      <button>Sign up</button>    </form>  );}
Output
> render> render> { email: 'rahul@gmail.com', password: 'secret123' }

53.4 A Zod schema

  • z.object describes in one place what the data should look like; every rule can carry its own message.
  • z.email() checks a valid email; z.string().min(8) needs at least 8 characters.
  • safeParse does not throw: it returns a result object with success true/false.
  • z.flattenError(result.error).fieldErrors gives the errors of each field separately.
JavaScript
import { z } from "zod"; export const schema = z.object({  email: z.email("Invalid email"),  password: z.string().min(8, "Min 8 chars"),}); const result = schema.safeParse({  email: "rahul",  password: "123",}); console.log(result.success);const errors = z.flattenError(result.error);console.log(errors.fieldErrors);
Output
> false> { email: [ 'Invalid email' ], password: [ 'Min 8 chars' ] }

53.5 Zod + React Hook Form (zodResolver)

  • zodResolver comes from @hookform/resolvers; pass it in the resolver option of useForm, so Zod does the validation.
  • Read errors from formState and show errors.email?.message below each field.
  • With invalid data both errors show and onSubmit does not run at all.
React (JSX)
function Signup() {  const { register, handleSubmit, formState } =    useForm({ resolver: zodResolver(schema) });  const { errors } = formState;  const onSubmit = (d) => console.log(d);  return (    <form onSubmit={handleSubmit(onSubmit)}>      <input {...register("email")} />      <p>{errors.email?.message}</p>      <input {...register("password")} />      <p>{errors.password?.message}</p>      <button>Sign up</button>    </form>  );}
Output
[ rahul ]Invalid email[ 123 ]Min 8 chars[button] Sign up
What happens on submit
  1. 1.User submits the form

  2. 2.handleSubmit collects the values of all fields

  3. 3.zodResolver checks the values against the schema

  4. 4.Valid: onSubmit(data) gets the clean data

  5. 5.Invalid: errors go into formState and only then the form re-renders

53.6 Validation modes: when does the error go?

  • Default mode "onSubmit": no error is shown before the first submit.
  • Default reValidateMode "onChange": after a submit, every change is validated again.
  • So when the user fixes the email to rahul@gmail.com, the error disappears immediately while typing.
JavaScript
export function useSignupForm() {  return useForm({    resolver: zodResolver(schema),    mode: "onSubmit",    reValidateMode: "onChange",  });}
Output
[ rahul ]Invalid email [ rahul@gmail.com ]
OptionValueEffect
mode"onSubmit" (default)First validation only on submit
mode"onBlur" / "onChange" / "all"Validate earlier, when leaving a field or on every change
reValidateMode"onChange" (default)After the first submit, re-validate on every change
reValidateMode"onBlur" / "onSubmit"Re-validate less often

53.7 Controller: custom components

  • register only works with native inputs.
  • Custom components (shadcn Select, date picker, StarRating) take value and onChange props, so use Controller.
  • Give Controller the name and the control from useForm; render receives field, pass field.value and field.onChange.
React (JSX)
function Review() {  const { control, handleSubmit } = useForm();  const onSubmit = (d) => console.log(d);  return (    <form onSubmit={handleSubmit(onSubmit)}>      <Controller        name="rating" control={control}        render={({ field }) => (          <StarRating value={field.value}            onChange={field.onChange} />        )} />      <button>Submit</button>    </form>  );}
Output
★★★★☆[button] SubmitConsole: { rating: 4 }

53.8 useFieldArray: a dynamic list

  • For forms where the number of items is unknown (group booking members).
  • useFieldArray({ control, name: "members" }) gives fields and functions like append (also remove, insert...).
  • Input names use the path members.${i}.name; the key is field.id, not the index.
React (JSX)
function Booking() {  const { register, control } = useForm();  const { fields, append } = useFieldArray({    control, name: "members",  });  const add = () => append({ name: "" });  return <>    {fields.map((field, i) => (      <input key={field.id}        {...register(`members.${i}.name`)} />    ))}    <button onClick={add}>Add member</button>  </>;}
Output
[ ][ ][button] Add member
Choosing how to connect a field
  1. 1.Is it a native input/select/textarea? Use register

  2. 2.Is it a custom component with value + onChange? Use Controller

  3. 3.Is it a list of repeated fields? Use useFieldArray

  4. 4.Is it a number? Add valueAsNumber or z.coerce.number()

53.9 Comparison: manual controlled form vs React Hook Form + Zod

PointManual (useState)React Hook Form + Zod
State per fieldvalue + error statesNone, values read via refs
Re-render while typingEvery keystrokeNo (only when read formState changes)
Validation rulesScattered in handlersOne Zod schema
Submit handlingManual preventDefaulthandleSubmit does it
Reuse on server / typesNoSame schema on server, z.infer for the type

53.10 Common mistakes

  • Number field: an input value is always a string, even with type="number", so z.number() fails with expected number, received string.
  • Fix: register("age", { valueAsNumber: true }) or z.coerce.number() in the schema.
  • Using register on a custom component instead of Controller.
  • Using the index as key in useFieldArray instead of field.id.
  • Trusting client validation only: the browser can be bypassed, always validate on the server too.
React (JSX)
// Wrong: "Invalid input: expected number, received string"const schema = z.object({  age: z.number().min(18),}); <input type="number"  {...register("age")} />
React (JSX)
// Right: { age: 25 }const schema = z.object({  age: z.number().min(18),}); <input type="number"  {...register("age", { valueAsNumber: true })} />

53.11 Interview tips

  • Why React Hook Form over controlled inputs? Inputs stay uncontrolled and values are read through refs, so the form does not re-render while typing.
  • formState is a proxy: the component re-renders only for the values it actually reads (like errors).
  • The Zod schema is the single source of truth: same rules in the form and on the server, and z.infer gives the TypeScript type.
  • Controller for custom components, useFieldArray for dynamic lists, valueAsNumber/coerce for numbers.