Skip to content

Form State ​

Keep one schema, validate on both sides of the wire, and stop re-rendering the whole form on every keystroke.

In this chapter: the draft lifecycle · controlled against uncontrolled · one schema, two runtimes · when to show an error · server-action forms · multi-step drafts

💡 The Core Idea ​

Form state is the only category that is invalid on purpose. A user typing an email address passes through "a", "al", "ali". None of those are email addresses, and telling them so at each step is hostile.

That one property is why forms do not belong in application state. Application state should be valid. A form is a draft that becomes valid at the end, if it becomes valid at all.

A form has a lifecycle, and every decision in this chapter attaches to a point in it:

text
pristine → dirty → validated → submitting → submitted or failed

How It Works ​

Controlled against uncontrolled ​

ControlledUncontrolled
Where the value livesReact stateThe DOM node
Re-render on keystrokeYes, every oneNo
Reading the valueAlways availableOn submit, or via a ref
Needed forLive formatting, dependent fields, live previewEverything else

A large controlled form re-renders on every character. With twenty fields and a validation pass per render, that is measurable input lag on a mid-range phone. It is the most common performance problem in enterprise forms.

React Hook Form is popular because it is uncontrolled underneath. Inputs register with the DOM, and the library subscribes to what it needs. Components re-render only when their own error state changes.

One schema, two runtimes ​

One rule matters more than any library choice: write the validation rules once and run them in both places. Client validation is a user-experience feature. Server validation is correctness. A rule that exists on only one side is either a security hole or a broken form.

typescript
import { z } from 'zod';

// Shared by the form and the endpoint. Zod 4 promotes formats to top level: z.email(), not z.string().email().
export const inviteSchema = z.object({
  email: z.email(),
  role: z.enum(['viewer', 'editor', 'admin']),
  message: z.string().max(500).optional(),
});

export type InviteInput = z.infer<typeof inviteSchema>;

With z.infer, Zod derives the TypeScript type from the runtime rules, so you do not declare it beside them. One definition, no drift.

⚠️ Moving target: Zod 4 moved string formats to top-level functions (z.email() replacing z.string().email()) and reorganised the error-issue types. The lasting idea is a single schema that produces both runtime validation and a static type. The call syntax will keep moving. Other validators that meet the same contract can be swapped in behind a resolver.

The form side:

typescript
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';

const { register, handleSubmit, formState } = useForm<InviteInput>({
  resolver: zodResolver(inviteSchema),
  mode: 'onTouched', // validate after first blur, then on change
});

const onSubmit = handleSubmit(async (values: InviteInput) => {
  await sendInvite(values); // values are already parsed and typed
});

The endpoint side runs the same schema:

typescript
const parsed = inviteSchema.safeParse(await request.json());
if (!parsed.success) {
  return Response.json({ errors: parsed.error.flatten() }, { status: 400 });
}

When to show an error ​

Validation timing is a user-experience decision. Get it wrong and forms feel aggressive.

ModeBehaviourVerdict
onSubmitErrors appear only after submittingSafe default; poor for long forms
onChangeErrors while typingHostile — flags every partial value
onBlurErrors when leaving a fieldGood
onTouchedBlur first, then live once touchedBest for most forms

onTouched is the pattern users expect. Say nothing until they have finished with a field, then correct them live while they fix it.

Whichever mode you choose, the error must reach assistive technology. Link the message to the input with aria-describedby, mark the field aria-invalid, and move focus to the first error on a failed submit. See Accessible Forms and Error Messaging.

Server-action forms ​

Server actions change where the submit handler lives, not what validation needs to be. The form posts to a server function. That function runs the same schema and returns field errors as data.

Two properties come with the pattern. The form works without JavaScript, because it is a real form posting to a real endpoint. And the errors it renders are the server's, so the two sides cannot disagree.

The cost is a round trip for every validation pass. So most production forms run the schema on the client too and treat the server as the authority. The mechanics (pending state, returned errors, progressive enhancement) are in Actions and Forms and Server Actions. The same idea in another framework is SvelteKit Form Actions.

Multi-step forms and where the draft lives ​

A wizard raises a question a single form does not: what happens when the user refreshes on step three?

ApproachSurvives refreshRight for
One form, steps as viewsNoShort flows finished in one sitting
Step in the URL, values in memoryStep onlyFlows where restarting is acceptable
Draft persisted to sessionStorageYes, on that deviceLong flows, no account needed
Draft saved to the server per stepYes, everywhereApplications, onboarding, anything long

Validate each step against a slice of the whole schema, and validate the whole schema again on final submit. A user who reaches the last step through a restored draft may not have passed step one under the current rules.

When to Use It ​

SituationApproach
Two or three simple fieldsUncontrolled inputs and a schema on submit
A typical business formReact Hook Form plus a shared schema, onTouched
Live formatting or dependent fieldsControlled, for those fields only
Progressive enhancement is requiredA server-action form, schema on both sides
A long application flowPersisted draft, per-step validation, full validation at the end

Common Mistakes ​

❌ Holding form values in a global store. ✅ Every keystroke then re-renders anything subscribed to it. Form state is local by nature. Only the submitted result belongs anywhere else.

❌ Writing the validation rules twice. ✅ They drift within a release. Export one schema and import it on both sides.

❌ Trusting client validation. ✅ It is a convenience for honest users. The endpoint must revalidate every field. See Input Validation.

❌ Validating on every change from the first keystroke. ✅ Users see an error before they have finished typing the first word. Use onTouched.

❌ Rendering an error message with no programmatic link to its input. ✅ A screen reader announces the field with no idea why it failed. Wire aria-describedby and aria-invalid.

❌ Resetting the form when fresh server data arrives mid-edit. ✅ You have discarded the user's work. Compare against the dirty fields and ask, or merge only the untouched ones.

🔑 Key Takeaways ​

  • Form state is invalid by design, which is why it does not belong in application state.
  • Uncontrolled inputs avoid a re-render per keystroke. Use controlled fields only where you need the value live.
  • One schema, imported by the form and the endpoint, produces both the runtime check and the static type.
  • Validate after first blur, then live. onTouched is the mode users expect.
  • Client validation is user experience. Server validation is correctness, and it is never optional.

Interview Questions ​

Q: Why are uncontrolled inputs the default in modern form libraries?

A controlled input re-renders the component on every keystroke. A large form then re-renders on every character typed anywhere in it. Uncontrolled inputs leave the value in the DOM. The library subscribes only to what changes, usually a single field's error state, so typing costs nothing.

Q: Where does validation belong when the server also validates?

Both places, from one schema. The client copy gives the user instant feedback without a round trip. The server copy exists because anyone can bypass the client entirely. Sharing one schema module stops the two from disagreeing, and inferring the TypeScript type from it removes a third copy.

Q: How do you decide when to show a validation error?

Not while the user is first typing a field. Every partial value is invalid, so live errors read as nagging. Validate on blur, then switch that field to live validation so the user sees corrections confirmed at once. On submit, show everything and move focus to the first error.

Q: A user is halfway through editing a record and a background refetch returns new server data. What do you do?

Do not overwrite the fields they have touched. Compare the incoming data with the dirty field set. Merge untouched fields silently. For touched ones, either leave them alone or show a conflict the user can resolve. Resetting the whole form is the common bug, and it destroys their work.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.