Appearance
6.4.14 — React Hook Form with Zod: Forms Without the Pain
On page 6.4.3 you built the checkout form by hand. It worked, and it needed a state object, a handler that knew about checkboxes, a validation function, an error state, and glue between them. Add ten more fields and a "gift recipients" list that grows when you press a button, and you are writing a small framework.
React Hook Form (often shortened to RHF) is a library that does the repetitive parts. Pair it with Zod from page 6.4.13 and the same schema decides what is valid and gives the form its types. This page rebuilds the checkout form with both, then adds the things real forms need: server errors, custom inputs, and lists of rows.
1. What is wrong with the hand-written form
Count what you did on page 6.4.3 for every field: a key in the state object, a value, an onChange, a branch in the validation function, and a spot to show the error. And there is a cost you cannot see. Every keystroke calls setValues, so the whole form component draws again for every letter typed. For five fields that is fine. For a long form with a heavy layout, typing starts to lag.
We measured it. Typing five letters into a hand-written controlled input drew the component 6 times (once at the start, once per letter). The same input with React Hook Form drew its component 2 times, both at startup, and zero times while typing.
The figure shows why. RHF does not copy each letter into React state. It lets the browser keep the text inside each input, and reads the values only when it needs them, such as when the user presses Submit (①, ②). It then checks them with your schema (③). If they are fine, your function runs (④a). If not, the error messages are stored and the form draws once to show them (④b).
This style, where the input holds its own value, is called an uncontrolled input. On page 6.4.2 you learned the opposite, the controlled input, where React state holds the value. Both are valid. RHF uses uncontrolled inputs by default because they are cheaper. It still gives you tools when you need control (section 8).
2. Install
bash
npm install react-hook-form zod @hookform/resolversreact-hook-form is the form engine. zod is the schema library. @hookform/resolvers is the small bridge that lets RHF ask a Zod schema "is this valid?". The bridge is called a resolver.
3. The schema first
We start from what is allowed, because the schema will also give us the type.
ts
// src/schemas/checkout.ts
import { z } from 'zod'
export const checkoutSchema = z.object({
name: z.string().trim().min(1, 'Please enter your name'), // (1)
email: z.email('Enter a valid email'),
country: z.enum(['PT', 'DE']),
quantity: z
.number({ error: 'Enter a quantity' }) // (2)
.int('Use a whole number')
.min(1, 'At least 1')
.max(10, 'At most 10'),
giftWrap: z.boolean(),
note: z.string().max(100, 'Keep the note under 100 characters'),
})
export type CheckoutValues = z.infer<typeof checkoutSchema> // (3)- A string rule with its own error message as the second argument. Whatever you write here is exactly what the user will see under the field.
quantityis a number. A form input always gives text, so we will tell RHF to convert it (section 4). The schema can then usez.number(). The message inz.number({ error: ... })is shown when the box is empty or is not a number. Without it, the user would see Zod's own wording,Invalid input: expected number, received NaN, which means nothing to a customer. We ran an empty box through the form and saw exactly that message before we added our own.- The TypeScript type of the form values, taken from the schema.
4. The form
tsx
// src/components/CheckoutForm.tsx
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { checkoutSchema } from '../schemas/checkout'
import type { CheckoutValues } from '../schemas/checkout'
export function CheckoutForm({ onOrder }: { onOrder: (values: CheckoutValues) => Promise<void> }) {
const {
register, // (1)
handleSubmit, // (2)
formState: { errors, isSubmitting }, // (3)
} = useForm<CheckoutValues>({
resolver: zodResolver(checkoutSchema), // (4)
defaultValues: { name: '', email: '', country: 'PT', quantity: 1, giftWrap: false, note: '' }, // (5)
})
return (
<form onSubmit={handleSubmit(onOrder)} noValidate> {/* (6) */}
<label>
Name
<input {...register('name')} aria-invalid={errors.name ? true : undefined} /> {/* (7) */}
</label>
{errors.name && <p role="alert">{errors.name.message}</p>} {/* (8) */}
<label>
Email
<input type="email" {...register('email')} />
</label>
{errors.email && <p role="alert">{errors.email.message}</p>}
<label>
Country
<select {...register('country')}>
<option value="PT">Portugal</option>
<option value="DE">Germany</option>
</select>
</label>
<label>
Quantity
<input type="number" {...register('quantity', { valueAsNumber: true })} /> {/* (9) */}
</label>
{errors.quantity && <p role="alert">{errors.quantity.message}</p>}
<label>
<input type="checkbox" {...register('giftWrap')} />
Gift wrap
</label>
<label>
Note
<textarea {...register('note')} />
</label>
{errors.note && <p role="alert">{errors.note.message}</p>}
<button type="submit" disabled={isSubmitting}> {/* (10) */}
{isSubmitting ? 'Placing order…' : 'Place order'}
</button>
</form>
)
}Here is what each numbered part does.
registerconnects one input to the form. You callregister('name')and spread the result onto the input with{...register('name')}. The spread (the three dots) copies whateverregisterreturns onto the element. It returns an object of four things: the field'sname, anonChangefunction, anonBlurfunction, and aref. Therefis how RHF reaches the real input to read its value. You do not write any of that. And because you typed'name'insideregister, TypeScript knows it must be one of the fields ofCheckoutValues. A typo such asregister('nmae')is a compile error.handleSubmitwraps your submit function. When the form is submitted, it reads all the values, checks them with the resolver, and only calls your function if everything is valid. It also callspreventDefaultfor you.formStateis an object about the form's current condition.errorsholds the error for each field.isSubmittingistruewhile your async submit function is running.zodResolver(checkoutSchema)is the bridge. This single line is why the form has no validation code of its own.defaultValuesare the starting values. Always give them. If you do not, an input starts asundefined, which causes a warning when the user begins typing and changes it from "uncontrolled" to "controlled".onSubmit={handleSubmit(onOrder)}: note that we callhandleSubmitwith our function and pass its result toonSubmit.noValidatestops the browser from showing its own pop-up messages on top of ours.aria-invalidtells screen readers that the field has an error.errors.nameexists only whennamefailed. Itsmessageis the string we wrote in the schema.- A number input still gives text to the form.
valueAsNumber: truemakes RHF convert it to a number before the schema sees it, soz.number()works. An empty box becomesNaN(JavaScript's "not a number" value), and the schema rejects it with the message from (2) above. - We disable the button while the submit function is running, so a double-click cannot place two orders. The function must return a promise for
isSubmittingto know when it finishes.
What happens, step by step
The user leaves the name empty, types nope as the email, and presses the button.
handleSubmitreads the values:name: '',email: 'nope', and so on.- It gives them to
checkoutSchema.safeParse, through the resolver. - Zod returns two issues:
name(Please enter your name) andemail(Enter a valid email). - RHF puts them in
formState.errors. The component draws once. Two<p role="alert">lines appear. - RHF moves keyboard focus to the first invalid field, which is the name box. We checked that the name input was the focused element after the failed submit. Your
onOrderwas not called.
Then the user fixes both fields and presses Submit again. The values pass, the errors clear, and onOrder is called with:
text
{ name: 'Ana', email: 'ana@example.com', country: 'PT', quantity: 1, giftWrap: false, note: '' }with quantity as a real number 1, and giftWrap as a real false, not the text "on" that a plain HTML checkbox would give. The types in onOrder match, because they all come from the one schema.
5. When do the errors appear?
By default, the first validation happens on submit. After a failed submit, each field re-checks as the user changes it, so the message disappears as soon as they fix it. This is the right default for most forms. You can change it with mode:
tsx
useForm<CheckoutValues>({
resolver: zodResolver(checkoutSchema),
mode: 'onTouched', // check a field after the user leaves it once, then on every change
})mode | First check happens | Good for |
|---|---|---|
'onSubmit' (default) | When the user submits | Short forms |
'onBlur' | When the user leaves a field | Long forms |
'onTouched' | When the user leaves a field, then on every change | A balanced feel |
'onChange' | On every keystroke | Password strength, live feedback (costs more re-renders) |
Other pieces of formState you will use: isDirty (the user has changed something), isValid (the form is currently valid; only tracked when mode is not 'onSubmit'), touchedFields, and dirtyFields. RHF only re-renders for the parts of formState that you read. That is why you destructure exactly what you need.
6. Reading values while the user types
Sometimes you must react to a value: show a gift message box only when "Gift wrap" is ticked.
tsx
import { useForm } from 'react-hook-form'
import type { SubmitHandler } from 'react-hook-form'
function GiftOptions() {
const { register, watch } = useForm<{ giftWrap: boolean; giftMessage: string }>({
defaultValues: { giftWrap: false, giftMessage: '' },
})
const giftWrap = watch('giftWrap') // (1)
return (
<>
<label>
<input type="checkbox" {...register('giftWrap')} />
Gift wrap
</label>
{giftWrap && <input {...register('giftMessage')} placeholder="Gift message" />}
</>
)
}watch('giftWrap')returns the current value and makes this component re-render whenever it changes. That is the price. Watch only what you must. For a value used just once, at submit, you do not needwatchat all.
Other ways to reach values: getValues('name') reads the current value without causing a re-render (good inside an event handler). setValue('name', 'Ana') sets one. reset() puts everything back to the defaults, and reset(newValues) loads new ones, which is how you fill an "edit" form after loading data from the server.
7. Errors that only the server knows
The schema can check the shape. It cannot know that an email is already registered. Only the server knows. The server's answer must show up next to the field, like any other error.
tsx
// src/components/SignupForm.tsx
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
const signupSchema = z.object({
email: z.email('Enter a valid email'),
password: z.string().min(8, 'Use at least 8 characters'),
})
type SignupValues = z.infer<typeof signupSchema>
async function createAccount(values: SignupValues): Promise<{ ok: true } | { ok: false; reason: 'email-taken' | 'down' }> {
// stand-in for a fetch to the server
return values.email === 'taken@example.com' ? { ok: false, reason: 'email-taken' } : { ok: true }
}
export function SignupForm() {
const { register, handleSubmit, setError, formState: { errors, isSubmitting } } = useForm<SignupValues>({
resolver: zodResolver(signupSchema),
defaultValues: { email: '', password: '' },
})
async function onSubmit(values: SignupValues) {
const result = await createAccount(values)
if (result.ok) return
if (result.reason === 'email-taken') {
setError('email', { type: 'server', message: 'That email already has an account' }) // (1)
} else {
setError('root', { type: 'server', message: 'We could not reach the server. Try again.' }) // (2)
}
}
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<input type="email" {...register('email')} placeholder="Email" />
{errors.email && <p role="alert">{errors.email.message}</p>}
<input type="password" {...register('password')} placeholder="Password" />
{errors.password && <p role="alert">{errors.password.message}</p>}
{errors.root && <p role="alert">{errors.root.message}</p>} {/* (3) */}
<button type="submit" disabled={isSubmitting}>Create account</button>
</form>
)
}setError('email', ...)puts a message on one field, as if the schema had produced it.type: 'server'is a label for your own use.setError('root', ...)is for an error that belongs to the whole form, not one field, such as "the server is down".- It is read like any other error, from
errors.root.
We ran it with taken@example.com. After the submit, the text "That email already has an account" appeared under the email field. This is the full path of a real signup. The schema checks the shape, the server checks the truth, and the user sees both in the same place.
8. Inputs that are not plain HTML: Controller
register works with real HTML inputs, because it needs a ref to the actual element. What about a custom component, such as a star rating, a date picker from a library, or a styled dropdown? It does not hand out a ref to an input. It only has a value and an onChange. For those, use Controller.
tsx
// src/components/ReviewForm.tsx
import { Controller, useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
const reviewSchema = z.object({
rating: z.number().min(1, 'Please pick a rating').max(5),
comment: z.string().min(5, 'Write at least 5 characters'),
})
type ReviewValues = z.infer<typeof reviewSchema>
function StarRating({ value, onChange }: { value: number; onChange: (stars: number) => void }) { // (1)
return (
<div role="radiogroup" aria-label="Rating">
{[1, 2, 3, 4, 5].map((star) => (
<button key={star} type="button" aria-pressed={value >= star} onClick={() => onChange(star)}>
{value >= star ? '★' : '☆'}
</button>
))}
</div>
)
}
export function ReviewForm({ onSave }: { onSave: (values: ReviewValues) => void }) {
const { control, register, handleSubmit, formState: { errors } } = useForm<ReviewValues>({
resolver: zodResolver(reviewSchema),
defaultValues: { rating: 0, comment: '' },
})
return (
<form onSubmit={handleSubmit(onSave)} noValidate>
<Controller
name="rating"
control={control} // (2)
render={({ field }) => <StarRating value={field.value} onChange={field.onChange} />} // (3)
/>
{errors.rating && <p role="alert">{errors.rating.message}</p>}
<textarea {...register('comment')} />
{errors.comment && <p role="alert">{errors.comment.message}</p>}
<button type="submit">Save review</button>
</form>
)
}StarRatingis an ordinary component. It knows nothing about forms. It takes avalueand callsonChangewith the new one.controlis the form's inner object.Controlleruses it to link the field to the form.renderreceivesfield, an object withvalue,onChange,onBlur,nameandref. We passvalueandonChangeto our component. Now it takes part in validation like any other field.
Controller makes that one field controlled, so that field re-renders as it changes. That is exactly the trade you want: controlled only where you need it, uncontrolled everywhere else.
9. Lists of rows: useFieldArray
An order can have several lines. The user can add a line, remove one, and each line has its own fields. The number of fields is not fixed. useFieldArray manages that.
tsx
// src/components/OrderLinesForm.tsx
import { useFieldArray, useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { z } from 'zod'
const orderSchema = z.object({
lines: z
.array(
z.object({
productId: z.string().min(1, 'Choose a product'),
quantity: z.number().int().min(1, 'At least 1'),
}),
)
.min(1, 'Add at least one line'), // (1)
})
type OrderValues = z.infer<typeof orderSchema>
export function OrderLinesForm({ onOrder }: { onOrder: (values: OrderValues) => void }) {
const { register, control, handleSubmit, formState: { errors } } = useForm<OrderValues>({
resolver: zodResolver(orderSchema),
defaultValues: { lines: [{ productId: '', quantity: 1 }] },
})
const { fields, append, remove } = useFieldArray({ control, name: 'lines' }) // (2)
return (
<form onSubmit={handleSubmit(onOrder)} noValidate>
{fields.map((field, index) => (
<div key={field.id}> {/* (3) */}
<select {...register(`lines.${index}.productId`)}> {/* (4) */}
<option value="">Choose…</option>
<option value="p1">Red mug</option>
<option value="p2">Desk lamp</option>
</select>
<input type="number" {...register(`lines.${index}.quantity`, { valueAsNumber: true })} />
<button type="button" onClick={() => remove(index)}>Remove</button>
{errors.lines?.[index]?.productId && <p role="alert">{errors.lines[index].productId.message}</p>} {/* (5) */}
</div>
))}
{errors.lines?.root && <p role="alert">{errors.lines.root.message}</p>}
<button type="button" onClick={() => append({ productId: '', quantity: 1 })}>Add line</button>
<button type="submit">Place order</button>
</form>
)
}- The schema says: a list of objects, and the list must not be empty.
useFieldArraygives youfields(the current rows) and functions to change them:append,remove, and others (insert,move,swap).- Use
field.idas the key. RHF creates a stable id for each row. Do not use the index, for the reason you saw on page 6.4.3: a deleted row would hand its state to the next one. - A path such as
`lines.${index}.productId`names one field inside a row. TypeScript checks it against the type, so a wrong path does not compile. - Errors follow the same path:
errors.lines[index].productId. An error about the list as a whole (no lines) is undererrors.lines.root.
We tested adding and removing. Starting with one row, two clicks on "Add line" gave three rows. Removing one left two. A submit while both rows had no product chosen blocked the order and showed "Choose a product" under each of those rows.
10. Connecting to TanStack Query
When the form submits, it usually sends data to a server. That is a mutation (page 6.4.11). The two libraries fit together simply: RHF decides when and with what to submit; the mutation does the sending.
tsx
// src/components/CheckoutWithMutation.tsx
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { checkoutSchema } from '../schemas/checkout'
import type { CheckoutValues } from '../schemas/checkout'
async function postOrder(values: CheckoutValues): Promise<{ orderId: string }> {
// stand-in for sendJson('/api/orders', 'POST', values)
return { orderId: `o-${values.name.length}` }
}
export function CheckoutWithMutation({ onDone }: { onDone: (orderId: string) => void }) {
const queryClient = useQueryClient()
const { register, handleSubmit, formState: { errors } } = useForm<CheckoutValues>({
resolver: zodResolver(checkoutSchema),
defaultValues: { name: '', email: '', country: 'PT', quantity: 1, giftWrap: false, note: '' },
})
const placeOrder = useMutation({
mutationFn: postOrder,
onSuccess: async ({ orderId }) => {
await queryClient.invalidateQueries({ queryKey: ['orders'] })
onDone(orderId)
},
})
return (
<form onSubmit={handleSubmit((values) => placeOrder.mutate(values))} noValidate> {/* (1) */}
<input {...register('name')} />
{errors.name && <p role="alert">{errors.name.message}</p>}
{placeOrder.isError && <p role="alert">Could not place the order: {placeOrder.error.message}</p>}
<button type="submit" disabled={placeOrder.isPending}> {/* (2) */}
{placeOrder.isPending ? 'Placing order…' : 'Place order'}
</button>
</form>
)
}handleSubmitruns only when the values are valid, then calls the mutation. The mutation receives values that already matchCheckoutValues.- We use the mutation's
isPendinghere, because the sending is done by the mutation. (If your submit function wereasyncand returned the promise,isSubmittingwould work too.)
11. When the schema changes the value: input and output types
So far, what the user types and what your function receives have had the same type. That is true as long as your schema has no transform, default, or coerce. When it does, the input and the output differ. For example, z.string().transform((s) => s.length) takes text and gives a number.
RHF then needs to be told both types, as three generic arguments:
tsx
type CheckoutInput = z.input<typeof schema> // what the form fields hold
type CheckoutOutput = z.output<typeof schema> // what handleSubmit gives your function
useForm<CheckoutInput, unknown, CheckoutOutput>({ resolver: zodResolver(schema) })The middle unknown is a slot for advanced use. Leave it as unknown. We compiled this form with all three generics and it type-checked.
A related warning: z.coerce.number() has an input type of unknown in Zod 4. We checked by assigning the text 'abc' to the input type, and it compiled. That means the form's field type loses its meaning. The cleaner pattern for numbers in forms, used in this page, is register('quantity', { valueAsNumber: true }) with z.number() in the schema. Reserve coerce for URL search params and other text-only sources.
12. Plain HTML rules, and why we skip them
RHF can validate without Zod, by passing rules to register:
tsx
<input {...register('name', { required: 'Please enter your name', minLength: { value: 2, message: 'Too short' } })} />This works well for one or two fields. We prefer Zod for three reasons. The rules live in one place, the schema, and are not scattered across the JSX. The same schema gives the type of the values. And the same schema can validate on the server, so a front-end check and a back-end check can never disagree.
What the interviewer will push on
"Why use React Hook Form instead of useState for forms?" Inputs are uncontrolled and registered through refs, so typing does not re-render the form. Less code, better performance, and built-in error and submit state. Say the measured fact: one render instead of one per keystroke.
"Controlled versus uncontrolled in RHF? When do you use Controller?" Default is uncontrolled via register. Use Controller (or useController) for components that are not plain inputs, such as custom dropdowns and date pickers, which only expose value and onChange.
"How do you add schema validation?" zodResolver(schema) in useForm. Derive the types with z.infer. Bring up z.input and z.output when the schema transforms.
"How do you show a server-side validation error?" setError('field', { message }) inside the submit handler, and setError('root', ...) for form-wide errors.
"How do you build a dynamic list of fields?" useFieldArray with fields, append, remove. Use field.id as the key, not the index.
"What does watch cost?" It re-renders the component on every change of the watched value. Use getValues inside handlers, or watch only specific fields, or useWatch in a small child component to keep the re-renders local.
One thing to volunteer: mention that you pass defaultValues always (to avoid uncontrolled-to-controlled warnings and to support reset), and that you use valueAsNumber rather than z.coerce for number inputs so the input type stays meaningful.
Recall
- Why RHF: inputs stay uncontrolled (the browser holds the text). Typing does not re-render the form. We measured 0 renders while typing, versus 5 for a controlled input (6 versus 2 in total, counting startup).
useForm<Values>({ resolver: zodResolver(schema), defaultValues })returnsregister,handleSubmit,formState,control,watch,setError,setValue,getValues,reset.{...register('field')}gives an input itsname,onChange,onBlurandref. The field name is type-checked against the values type.handleSubmit(fn)reads the values, validates, and callsfnonly if valid. It callspreventDefaultfor you. It focuses the first invalid field.formState.errors.field?.messageshows the schema's message.isSubmittingis true while an async submit runs. Read only what you need.isDirty,isValid,touchedFieldsexist too.mode:'onSubmit'(default),'onBlur','onTouched','onChange'.- Numbers:
register('qty', { valueAsNumber: true })plusz.number(). Checkboxes give real booleans.z.coerce.number()has input typeunknown. watch('x')re-renders on every change.getValuesdoes not.- Server errors:
setError('email', { type: 'server', message }); whole-form errors withsetError('root', ...), read fromerrors.root. Controller(control,name,render={({ field }) => ...}) for custom components.useFieldArray({ control, name })givesfields,append,remove; key byfield.id; paths like`lines.${i}.qty`.- Always give
defaultValues. When the schema transforms, useuseForm<z.input<S>, unknown, z.output<S>>.
Self-test: Why does typing in an RHF field not re-render the form? · What does {...register('name')} give the input? · What does handleSubmit do before calling your function? · When would you use Controller? · Why use field.id and not the index as the key in useFieldArray?
Next: 6.4.15 puts every piece from the last nine pages into one small, working shop: a router, a query cache, a cart store, and a validated checkout form, and shows which tool owns which kind of state.