Advanced React 03 · Forms
Forms in practice: React Hook Form
Big forms without the plumbing: register and Zod, errors after leaving a field, errors from the server, custom controls and repeating rows.
Loading lesson…
Advanced React 03 · Forms
Big forms without the plumbing: register and Zod, errors after leaving a field, errors from the server, custom controls and repeating rows.
Loading lesson…
From lesson Advanced React 01 you know a form with an action, and from lesson Advanced React 02 rules in a schema. That's enough for sign-in or a contact form. But now take a sign-up with ten fields, where an error should show as soon as a field is left, not only after submitting. You have to write this yourself (and this is a shortened version of the challenge in lesson 01):
function Signup() {const [values, setValues] = useState({ name: '', email: '', password: '', /* …7 more fields */ })// Record<string, boolean> = an object whose keys are strings and values true/false: { name: true, email: false }const [touched, setTouched] = useState<Record<string, boolean>>({}) // which fields the user has leftconst [submitted, setSubmitted] = useState(false) // tried to submit?const [isSubmitting, setIsSubmitting] = useState(false) // is it submitting?const result = SignupSchema.safeParse(values) // the errors are calculated on every renderconst errors = result.success ? {} : z.flattenError(result.error).fieldErrorsconst show = (f: string) => (touched[f] || submitted) && errors[f]?.[0]function handleChange(e) { setValues((v) => ({ ...v, [e.target.name]: e.target.value })) }function handleBlur(e) { setTouched((t) => ({ ...t, [e.target.name]: true })) }async function handleSubmit(e) { /* preventDefault, submitted, isSubmitting, try/catch… */ }// …and value, onChange, onBlur and {show('…')} at each of the ten fields}
It works. But:
React Hook Form is a library that contains this plumbing. You tell it what the fields and rules are (a Zod schema), and it keeps track of the values, the left fields, the errors, submitting and the cursor. It keeps the values right in the fields (uncontrolled, like FormData), so typing doesn't re-render the whole form. You add it to a project with npm install react-hook-form @hookform/resolvers (the second package connects it to Zod).
Let's stay at the town hall from the lesson on forms. The clerk over your shoulder (a controlled field) checks every letter – and interrupts. The front desk (an action) checks everything only when you hand it in. An experienced clerk does it more cleverly: she has a list of rules (the schema), lets you fill in a field in peace, and when you move on to the next one she says "this is wrong". When you hand it in, she points at the first error. And all along she remembers what you've filled in and what you haven't.
The table shows typical forms; on the right is what's used for them in practice:
| Form | What to use |
|---|---|
| sign-in, a newsletter, a comment (a few fields, errors after submitting are enough) | an action + Zod (lessons 01 and 02) |
| a form that must be submittable even without JavaScript (Next.js) | an action + Zod |
| sign-up, a profile, an order (more fields, errors after leaving a field) | ✅ React Hook Form + Zod |
| repeating rows (order items, contacts) | ✅ React Hook Form – useFieldArray |
| a multi-step wizard, fields depending on other fields | ✅ React Hook Form |
import { useForm } from 'react-hook-form'import { zodResolver } from '@hookform/resolvers/zod'// 1. THE RULES – a Zod schema (lesson Advanced React 02)const MySchema = z.object({ field: z.string().min(1, 'Required field') })type Values = z.infer<typeof MySchema>function MyForm() {// 2. THE FORM – useForm returns tools for the fields and the form's stateconst { register, handleSubmit, formState: { errors } } = useForm<Values>({resolver: zodResolver(MySchema), // the schema does the checkingdefaultValues: { field: '' }, // each field's initial value})// 3. SUBMITTING – called only when the data passed the schemafunction onSubmit(values: Values) { /* … */ }return (<form onSubmit={handleSubmit(onSubmit)}><input {...register('field')} /> {/* attach the field */}{errors.field && <p>{errors.field.message}</p>} {/* show the error */}<button>Submit</button></form>)}
Writing const { register, handleSubmit, formState: { errors } } = useForm(…) is unpacking an object from JavaScript 03, just one level deeper: from the object useForm returns, take register and handleSubmit, and from its formState property also errors. It's a shorter way of writing const errors = form.formState.errors.
Three questions come with a form:
Values type and defaultValues.zodResolver attaches it.onSubmit – it gets already checked data.const NewsletterSchema = z.object({ email: z.email('Invalid e-mail') })type Values = z.infer<typeof NewsletterSchema> // { email: string }function Newsletter() {const { register, handleSubmit, formState: { errors } } = useForm<Values>({resolver: zodResolver(NewsletterSchema),defaultValues: { email: '' },})return (<form onSubmit={handleSubmit((values) => subscribe(values.email))} noValidate><label><input type="email" {...register('email')} /></label>{errors.email && <p className="field-error">{errors.email.message}</p>}<button>Subscribe</button></form>)}// subscribe = a made-up function "sign up for the newsletter"
What happens after clicking "Subscribe":
onSubmit. That's the function handleSubmit(…) returned – it calls preventDefault by itself so the page doesn't reload.zodResolver.errors (errors.email.message is the schema's message), puts the cursor into the first wrong field and doesn't call your function.noValidate turns off the browser's bubbles from lesson 01 – otherwise the messages would show twice (a bubble and your message).
register('email') returns an object with name, onChange, onBlur and ref. Writing {...register('email')} spreads them onto the field as attributes (spread from JavaScript 10). Through the ref React Hook Form "holds on" to the field (a ref from Hooks 02) and reads the value from it when it needs to – that's why you don't write value or useState.
The second argument of register says how to treat the value:
| I want… | Code | Note |
|---|---|---|
| a number instead of text | register('age', { valueAsNumber: true }) | an empty field gives NaN – the schema rejects it |
| a date instead of text | register('birth', { valueAsDate: true }) | for type="date" |
| a checkbox | <input type="checkbox" {...register('agree')} /> | the value is true/false |
| a choice from a list | <select {...register('size')}>…</select> | the value is the chosen option’s value |
valueAsNumber is the counterpart of z.coerce.number() from the lesson on Zod: the field returns text, the schema expects a number, and here React Hook Form does the conversion before the schema.
The mode option of useForm decides when a field is checked. The table shows the options; in practice onTouched is used most often:
| mode | When a field is first checked | When it suits |
|---|---|---|
'onSubmit' | on submit (the default) | short forms |
'onBlur' | after leaving the field | when you don’t want to check while typing at all |
'onTouched' | after leaving the field, then on every change | ✅ most forms – an error disappears as soon as you fix it |
'onChange' | on every letter | only exceptionally – it interrupts |
formState is an object with what React Hook Form knows about the form. These properties are needed most often:
| Property | What it says | Typical use |
|---|---|---|
errors | errors by field | errors.email?.message |
isSubmitting | an asynchronous onSubmit is running | disable the button, "Saving…" |
isDirty | the user changed some value | "You have unsaved changes" |
isValid | the form would pass the schema now | highlight the button |
touchedFields | which fields the user has left | your own display logic |
All five properties in one form for editing a profile:
// inside the component; ProfileSchema = a Zod schema, Values = the type from it (z.infer)const {register,handleSubmit,formState: { errors, isSubmitting, isDirty, isValid, touchedFields }, // take what you'll read} = useForm<Values>({resolver: zodResolver(ProfileSchema),mode: 'onTouched',defaultValues: { name: 'Jane' }, // the form starts with this value})// save = a made-up asynchronous "save to the server" function; while it runs, isSubmitting is truereturn (<form onSubmit={handleSubmit(save)} noValidate><input {...register('name')} />{/* errors: the message from the schema for the name field */}{errors.name && <p className="field-error">{errors.name.message}</p>}{/* touchedFields: the user has already left the field – and it has no error */}{touchedFields.name && !errors.name && <p>✓ Looks good</p>}{/* isDirty: the value differs from defaultValues (type "Jane" back and it's false again) */}{isDirty && <p>You have unsaved changes.</p>}{/* isValid: the data would pass the schema now → highlight the button; isSubmitting: saving → disable it */}<button className={isValid ? 'btn btn-ready' : 'btn'} disabled={!isDirty || isSubmitting}>{isSubmitting ? 'Saving…' : 'Save'}</button></form>)
Why unpack the properties right where you call useForm and not later? React Hook Form notices which of them the component reads and renders it again only when exactly those change. A property you don't read while rendering isn't watched – and causes no needless re-renders either.
A schema checks the shape of the data, but some errors are known only to the server – say "this e-mail is already registered". You put such an error into the form by hand with setError, and it shows at the field just like an error from the schema:
// inside the sign-up component; SignupSchema = a Zod schema, Values = the type from it (z.infer)const { register, handleSubmit, setError, reset, formState: { errors, isSubmitting } } = useForm<Values>({resolver: zodResolver(SignupSchema),mode: 'onTouched',defaultValues: { name: '', email: '' },})async function onSubmit(values: Values) { // async – React Hook Form waits, and meanwhile isSubmitting is truetry {await registerUser(values)reset() // done → clear the form back to defaultValues} catch (e) {setError('email', { message: (e as Error).message }) // an error from the server at the e-mail field}}// in the JSX: handleSubmit first checks the schema, and only when the data passes does it call onSubmit// <form onSubmit={handleSubmit(onSubmit)} noValidate> … <button disabled={isSubmitting}>Sign up</button></form>
What you see: A sign-up with mode: 'onTouched', a Zod schema, an error from the server and a button that's disabled while submitting. At the bottom you see isDirty.
Try it:
@taken.com and tick the consent. After submitting, the error from the server shows at the e-mail.isDirty: it changes to true as soon as you type anything.The takeaway: The library keeps track of left fields, errors, submitting and errors from the server. You wrote the rules and what should happen on submit.
Loading the interactive part…
register works with ordinary fields (input, select, textarea), because it needs a ref to a real field and its change event. But a custom component like a star rating or a date picker from a library has no field – it has value and onChange. That's what Controller is for: it makes a form field "controlled":
import { Controller } from 'react-hook-form'// A custom component: five stars, value = the count, onChange = the new countfunction StarRating({ value, onChange }: { value: number; onChange: (v: number) => void }) {return [1, 2, 3, 4, 5].map((n) => (<button key={n} type="button" onClick={() => onChange(n)}>{n <= value ? '★' : '☆'}</button>))}const { control, handleSubmit } = useForm<{ rating: number }>({ defaultValues: { rating: 0 } })<Controllername="rating" // which form fieldcontrol={control} // the link to useForm// render = a function that gets the field's tools and returns the JSX to render// (such a prop is called a render prop – lesson Advanced React 05)render={({ field }) => ( // field = { value, onChange, onBlur, name, ref }<StarRating value={field.value} onChange={field.onChange} />)}/>
Controller gives the component the current value and the function to call on a change – exactly the props a controlled component needs (React basics 04). Checking with the schema, errors and submitting work the same as with register.
Some parts of a form depend on another field's value: "I'm a company" ticked → show the "Company ID" field. Because React Hook Form keeps the values in the fields and doesn't re-render while typing, you have to ask for the value:
import { useWatch } from 'react-hook-form'const { control, register } = useForm<Values>({ defaultValues: { isCompany: false, companyId: '' } })const isCompany = useWatch({ control, name: 'isCompany' }) // re-renders only when this field changes<label><input type="checkbox" {...register('isCompany')} /> I'm a company</label>{isCompany && <input {...register('companyId')} placeholder="Company ID" />}
useWatch watches only the fields you tell it to and re-renders the component only when they change – the other fields still don't re-render while typing.
What for: order items, several phone numbers, a list of participants – a group of fields the user adds and removes. useFieldArray keeps the array of rows and gives you functions to change it:
// the file with the order form: the schema above the component, useForm and useFieldArray inside the component, fields.map in its JSXconst OrderSchema = z.object({items: z.array(z.object({name: z.string().min(1, 'Fill in the name'),qty: z.number().int().min(1, 'At least 1 piece'),})).min(1, 'Add at least one item'),})type Order = z.infer<typeof OrderSchema> // { items: { name: string; qty: number }[] }const { control, register, formState: { errors } } = useForm<Order>({resolver: zodResolver(OrderSchema),defaultValues: { items: [{ name: 'Apple', qty: 3 }] },})// useFieldArray is imported from 'react-hook-form'; name: 'items' = which field of the schema holds the rowsconst { fields, append, remove } = useFieldArray({ control, name: 'items' }){fields.map((field, index) => (<div key={field.id}> {/* field.id – a stable key (React basics 02) */}<input {...register(`items.${index}.name`)} /> {/* the field name with the row's index */}<input type="number" {...register(`items.${index}.qty`, { valueAsNumber: true })} />{errors.items?.[index]?.name && <p>{errors.items[index].name.message}</p>}<button type="button" onClick={() => remove(index)}>✕</button></div>))}<button type="button" onClick={() => append({ name: '', qty: 1 })}>+ Item</button>
fields are the rows to render. Each has an id that doesn't change – use it as the key, not the index.items.0.name, items.1.qty. By it React Hook Form puts the values back together into an array of objects.type="button" – otherwise a button inside a form would submit the form.What you see: An order with one item. Below the rows is the total number of pieces, calculated through useWatch.
Try it:
The takeaway: Repeating rows are an array of objects in the schema and in the form. useFieldArray handles adding, removing and errors at individual rows.
Loading the interactive part…
This section puts the lesson together into a template to come back to when you write your own form. You'll find the same pattern in the Cheat sheets on the React tab.
// the file src/components/ProfileForm.tsximport { useForm } from 'react-hook-form'import { zodResolver } from '@hookform/resolvers/zod'import { z } from 'zod'// 1. THE RULES – a Zod schema and the type from itconst ProfileSchema = z.object({name: z.string().trim().min(2, 'The name must have at least 2 characters'),email: z.email('Invalid e-mail'),// z.number, not z.coerce: register with valueAsNumber does the conversion (below)age: z.number('The age must be a number').int().min(18, 'You must be at least 18'),})type Profile = z.infer<typeof ProfileSchema>export function ProfileForm() {// 2. THE FORM – take the tools you need from useFormconst { register, handleSubmit, setError, reset, formState: { errors, isSubmitting } } = useForm<Profile>({resolver: zodResolver(ProfileSchema), // the schema does the checkingmode: 'onTouched', // an error after leaving the field, then on every changedefaultValues: { name: '', email: '' }, // age has no initial value → the age field starts empty})// 3. SUBMITTING – called only with checked data; async → meanwhile isSubmitting is trueasync function onSubmit(values: Profile) {try {await saveProfile(values) // saveProfile = a made-up server functionreset(values) // the saved values = the new initial ones → isDirty is false again} catch (e) {setError('root', { message: (e as Error).message }) // an error of the whole form, not one field}}// 4. THE LOOK – for every field: a label, register, the error below itreturn (<form onSubmit={handleSubmit(onSubmit)} noValidate> {/* noValidate = no browser bubbles */}<label>Name{/* aria-invalid = a screen reader knows the field is wrong (lesson Advanced React 01) */}<input {...register('name')} autoComplete="name" aria-invalid={errors.name ? true : undefined} /></label>{errors.name && <p className="field-error">{errors.name.message}</p>}<label><input type="email" {...register('email')} autoComplete="email" aria-invalid={errors.email ? true : undefined} /></label>{errors.email && <p className="field-error">{errors.email.message}</p>}<label>Age{/* valueAsNumber = store a number in the form, not text */}<input type="number" {...register('age', { valueAsNumber: true })} /></label>{errors.age && <p className="field-error">{errors.age.message}</p>}{errors.root && <p className="field-error">{errors.root.message}</p>} {/* the error from the server */}<button disabled={isSubmitting}>{isSubmitting ? 'Saving…' : 'Save'}</button></form>)}// use in a parent: <ProfileForm />
setError('root', …) is an error that belongs to no field ("the server isn't responding"). reset(values) after saving sets the saved values as the new initial ones – isDirty goes back to false.
zodResolver, not scattered over the component.defaultValues (an empty text instead of undefined) and a label.valueAsNumber, custom components Controller.mode: 'onTouched', the form has noValidate and the errors are at the fields.setError; the button is disabled during isSubmitting.useFieldArray with key={field.id} and the buttons have type="button".Two places from the template in section 1: attach the field and show the error.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
The challenge goes through sections 1 and 2: attaching the schema, a number from a field, errors after leaving a field and an error from the server. For the form, first tell yourself: which fields and what they start with, what the rules are and what happens on submit.
Four changes that turn the form into a form as it's written in practice. What exactly should happen is in the comments in the code.
Task is in the comments in the code below – at the top of the file and at the places marked TODO.
Loading the interactive part…
defaultValues), what the rules are (a schema + zodResolver), what happens on submit (onSubmit with checked data).valueAsNumber for numbers), Controller a custom component with value and onChange.useForm, zodResolver, z)useForm – from the library react-hook-form: a library for forms (lesson Advanced React 03).zodResolver – from the library @hookform/resolvers/zod: connects a Zod schema to React Hook Form (lesson Advanced React 03).z – from the library zod: a library for checking data against a schema (lesson Advanced React 02).row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).useForm, zodResolver, z)useForm – from the library react-hook-form: a library for forms (lesson Advanced React 03).zodResolver – from the library @hookform/resolvers/zod: connects a Zod schema to React Hook Form (lesson Advanced React 03).z – from the library zod: a library for checking data against a schema (lesson Advanced React 02).row, stack, card, list, btn, input or muted are the course's ready-made styles in src/styles.css (row = side by side, stack = stacked, card = bordered box, muted = grey text).