URL and form state

Search params as state, React Hook Form and Zod.

Builds on Kinds of state, Forms.

Two kinds of state from Kinds of state don't belong in a store at all. URL state is state the user should be able to bookmark, share and move through with the Back button: the current filters, search, page, selected tab. Its home is the address bar. Form state is everything about a form before it's submitted: values, which fields were touched, errors, whether it's submitting. Its natural home is the form itself, and often the DOM.

Both are easy to get subtly wrong by reaching for useState, and both have small, focused tools. This chapter builds URL state from scratch, then shows nuqs, and moves on to forms with React Hook Form and Zod, building on the controlled and uncontrolled inputs from Forms.

The problem: filters that forget#

Here's the reading list with a tag filter and a search box, kept in useState.

function BookFilters() {
  const [tag, setTag] = useState("all");
  const [q, setQ] = useState("");
  // ...filter books by tag and q
}

It works until the user does any of these:

  • Refreshes: the filters reset.
  • Shares the link: the colleague sees the unfiltered list.
  • Clicks a book, then Back: the list component remounts and the filters are gone.
  • Presses Back expecting the previous filter: the browser leaves the page instead, because filter changes never created history entries.

The filters are part of where the user is, and the browser already has a place for that, with sharing, bookmarking and history built in. Keeping a copy in useState is the two-copies-of-the-truth problem from chapter 1 again.

Build it: search params as state#

The rule is simple: the URL is the single source of truth. Components read filters from the URL, and changing a filter means changing the URL. Two browser APIs do the writing:

  • history.pushState(state, "", url) adds a new history entry. Use it for discrete navigation-like changes (picking a tag, changing a page), so Back undoes them.
  • history.replaceState(state, "", url) updates the current entry in place. Use it for high-frequency changes like typing, so each keystroke isn't a Back stop.

Neither fires an event in the page that called it, so a real implementation notifies its own subscribers after writing, and listens to popstate for Back and Forward. That's a tiny external store with useSyncExternalStore once again.

The sandbox can't change its real URL, so it captures pushState and replaceState into a virtual URL (shown above the preview) and exposes it through useVirtualLocation() from guide-tools, which is exactly such an external store. The Back button below is a simulation of the browser's, built on a small stack.

Filters in the URL
import { books } from "guide-tools";
import { useSearchParams, setParam, simulateBack } from "./searchParams";

const tags = ["all", ...new Set(books.flatMap((b) => b.tags))];

export default function App() {
  const params = useSearchParams();
  const tag = params.get("tag") ?? "all"; // parse with a default
  const q = params.get("q") ?? "";

  const visible = books.filter(
    (b) => (tag === "all" || b.tags.includes(tag)) && b.title.toLowerCase().includes(q.toLowerCase()),
  );

  return (
    <div>
      <button onClick={simulateBack}>← Back (simulated)</button>
      <p>
        {tags.map((t) => (
          <button key={t} onClick={() => setParam("tag", t === "all" ? "" : t)} style={{ fontWeight: t === tag ? 700 : 400, marginRight: 4 }}>
            {t}
          </button>
        ))}
      </p>
      <input placeholder="Search titles" value={q} onChange={(e) => setParam("q", e.target.value, { replace: true })} />
      <ul>
        {visible.map((b) => (
          <li key={b.id}>{b.title}</li>
        ))}
      </ul>
    </div>
  );
}

Pick a tag, then another, type a search, and press Back twice: you walk back through the tags, and the typing collapsed into one entry. The input is controlled by the URL: its value comes from the search params, and typing writes the URL, which re-renders the component.

The URL as the single source of truth
Address barexample.com/booksFilter controlspushStateuseSearchParams()subscribe + readBook listall 10 bookswritenotifyHistory stack/books▲ current entry
Step 1 of 5

The URL is the source of truth. Components don't keep their own copy of the filters; they read them from the URL and subscribe to changes.

Three details make URL state solid in production:

  1. Parse and validate. Everything in the URL is a string the user can edit. ?page=banana must not crash the page: parse with defaults, clamp ranges, and ignore unknown values. A Zod schema (later in this chapter) is a good fit.
  2. Keep the URL canonical. Remove params that equal the default (tag=all is noise), so equal states have equal URLs, which also helps caching and analytics.
  3. Debounce expensive reactions, not the URL. Write the URL on every keystroke with replaceState, and debounce or defer the fetch or the filtering that depends on it.

In real routers, and nuqs#

Every router exposes search params. In Next.js, useSearchParams() from next/navigation reads them in Client Components (and the page's searchParams prop reads them on the server), and you write with router.push or router.replace. React Router has its own useSearchParams hook that returns the params and a setter. Both leave parsing, defaults and serialization to you.

nuqs is a small library that makes a search param feel like useState: typed parsers, defaults, and history options, with adapters for Next.js, React Router, TanStack Router and plain React. It isn't in the sandbox, so here's the shape:

app/layout.tsx
import { NuqsAdapter } from "nuqs/adapters/next/app";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <NuqsAdapter>{children}</NuqsAdapter>
      </body>
    </html>
  );
}

Setting a value back to its default removes the key from the URL (the canonical-URL rule above); that's the clearOnDefault option, which nuqs 2 turns on by default. By default nuqs updates are client-side only; in Next.js you opt in with the shallow: false option when a change should re-render Server Components that read searchParams.

Quick checkpush or replace

A search box writes its text to ?q= on every keystroke. Which history method should it use?

Fix itPut the filter in the URL

The tag filter lives in useState, so it's lost on refresh and can't be shared. Make the URL (?tag=...) the only source of truth: clicking a tag must update the URL, and changing the URL from outside must update the list. Use useVirtualLocation and history.pushState.

import { useState } from "react";
import { books } from "guide-tools";

const tags = ["craft", "systems", "fundamentals"];

export default function App() {
  const [tag, setTag] = useState<string | null>(null);
  const visible = tag ? books.filter((b) => b.tags.includes(tag)) : books;
  return (
    <div>
      {tags.map((t) => (
        <button key={t} onClick={() => setTag(t)}>
          {t}
        </button>
      ))}
      <ul>
        {visible.map((b) => (
          <li key={b.id}>{b.title}</li>
        ))}
      </ul>
    </div>
  );
}

Form state: what a form actually tracks#

A form has more state than its values:

  • values of every field, and the default values to compare against (is it dirty?);
  • touched and dirty flags per field, so errors appear at the right time;
  • errors per field, from synchronous rules, schemas, or the server;
  • submission state: submitting, submitted, submit count.

Forms showed the two ways to hold values. Controlled inputs keep each value in React state, so every keystroke re-renders the component that owns it. Uncontrolled inputs leave the value in the DOM and read it when needed. For a big form, controlled re-renders add up, and a single useState object at the top re-renders the whole form per keystroke.

React Hook Form: uncontrolled by design#

React Hook Form (RHF, version 7.92 in the sandbox) takes the uncontrolled side on purpose. register("title") returns { name, onChange, onBlur, ref }. RHF keeps a ref to each DOM input, stores values in its own internal store outside React state, and reads them when it validates or submits. Typing doesn't re-render anything unless something subscribed to that change.

Type into both forms and compare the render counters:

Controlled form versus React Hook Form
import { useState } from "react";
import { useForm } from "react-hook-form";
import { Rendered } from "guide-tools";

function ControlledForm() {
  const [values, setValues] = useState({ title: "", author: "" });
  return (
    <Rendered label="useState form">
      <input placeholder="Title" value={values.title} onChange={(e) => setValues({ ...values, title: e.target.value })} />{" "}
      <input placeholder="Author" value={values.author} onChange={(e) => setValues({ ...values, author: e.target.value })} />
    </Rendered>
  );
}

function HookForm() {
  const { register, handleSubmit } = useForm({ defaultValues: { title: "", author: "" } });
  return (
    <Rendered label="React Hook Form">
      <form onSubmit={handleSubmit((data) => console.log("submitted", data))}>
        <input placeholder="Title" {...register("title")} /> <input placeholder="Author" {...register("author")} />{" "}
        <button>Submit</button>
      </form>
    </Rendered>
  );
}

export default function App() {
  return (
    <>
      <ControlledForm />
      <HookForm />
    </>
  );
}

The controlled form re-renders on every keystroke; the RHF form doesn't. Submit and the values arrive in the console anyway, read from the inputs.

formState is a subscription#

formState (errors, isDirty, isSubmitting, isValid, touchedFields...) is wrapped in a proxy. RHF records which properties your component reads and only re-renders it when those change. That's the same read-tracking trick as Valtio's snapshots from the previous chapters. The consequence: read the properties you need during render (destructure them), or RHF won't know you care.

const {
  register,
  handleSubmit,
  formState: { errors, isSubmitting }, // subscribed to errors and isSubmitting only
} = useForm<BookInput>({ mode: "onTouched" });

Useful knobs:

  • mode: when validation first runs. "onSubmit" (default), "onBlur", "onChange", "onTouched" (on first blur, then on every change), "all". After a failed submit, reValidateMode (default "onChange") re-checks as the user fixes things.
  • handleSubmit(onValid, onInvalid?): validates, then calls onValid with the values. If onValid returns a promise, isSubmitting is true until it settles.
  • watch / useWatch: subscribe to values when the UI must react to them (a field that appears when a checkbox is ticked). useWatch isolates the re-render to the component that calls it.
  • reset, setValue, setError (for server errors), useFieldArray for dynamic lists of fields.

Controller for controlled components#

Some inputs can't be registered with a ref: a third-party select, a date picker, a custom rating widget. They want value and onChange. Controller (or the useController hook) bridges them: RHF still owns the value, and the component is controlled through the field object it receives.

import { Controller, useForm } from "react-hook-form";

function Stars({ value, onChange }: { value: number; onChange: (n: number) => void }) {
  return (
    <span>
      {[1, 2, 3, 4, 5].map((n) => (
        <button type="button" key={n} onClick={() => onChange(n)}>
          {n <= value ? "★" : "☆"}
        </button>
      ))}
    </span>
  );
}

function ReviewForm() {
  const { control, handleSubmit } = useForm({ defaultValues: { rating: 0 } });
  return (
    <form onSubmit={handleSubmit(console.log)}>
      <Controller
        name="rating"
        control={control}
        rules={{ min: { value: 1, message: "Pick a rating" } }}
        render={({ field, fieldState }) => (
          <>
            <Stars value={field.value} onChange={field.onChange} />
            {fieldState.error && <p>{fieldState.error.message}</p>}
          </>
        )}
      />
      <button>Save</button>
    </form>
  );
}

Only the Controller re-renders when the rating changes, not the whole form.

PredictRenders while typing

In the comparison sandbox above, you type "Dune" (four characters) into each form's Title field. By how much does each form's render count go up, and what would you have to add to the RHF form to make it re-render while typing?

Zod: one schema for types and validation#

Hand-written rules (required, min, pattern) work for small forms, but you end up describing the same shape three times: the TypeScript type, the client validation, and the server validation. Zod (version 4.6 in the sandbox) lets you write the shape once as a schema that validates at runtime and produces the TypeScript type.

Zod 4: parse, safeParse and error formatting
import { z } from "zod";

const BookInput = z.object({
  title: z.string().trim().min(1, { error: "Title is required" }),
  author: z.string().trim().min(2, { error: "Author needs at least 2 characters" }),
  year: z.number({ error: "Year must be a number" }).int().min(1450).max(2026),
  tags: z.array(z.string()).default([]),
});

// The static type comes from the schema:
// type BookInput = z.infer<typeof BookInput>;
// { title: string; author: string; year: number; tags: string[] }

const good = BookInput.safeParse({ title: "  Dune ", author: "Frank Herbert", year: 1965 });
console.log("success:", good.success, good.data); // trimmed title, tags defaulted to []

const bad = BookInput.safeParse({ title: "", author: "F", year: Number.NaN });
if (!bad.success) {
  console.log("issues:", bad.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`));
  console.log("flattened:", z.flattenError(bad.error).fieldErrors);
  console.log(z.prettifyError(bad.error));
}

try {
  BookInput.parse({}); // parse throws a ZodError instead of returning a result
} catch (e) {
  console.log("parse threw:", e instanceof z.ZodError);
}
Nothing logged yet.

The API to know:

  • schema.parse(input) returns typed, transformed data or throws a ZodError. schema.safeParse(input) returns { success: true, data } or { success: false, error } and never throws. Use safeParse at boundaries (forms, URL params, API responses) and handle both branches.
  • z.infer<typeof Schema> gives the output type; parsing also transforms (.trim(), .default(), z.coerce.number() for strings that should be numbers).
  • error.issues is the list of problems, each with a path and message. Zod 4 adds top-level helpers: z.flattenError(err) ({ formErrors, fieldErrors }, good for flat forms), z.treeifyError(err) for nested shapes, and z.prettifyError(err) for logs.

Plugging Zod into React Hook Form#

RHF accepts a resolver: a function (values) => { values, errors } that replaces its built-in rules. In a real project you install @hookform/resolvers and write useForm({ resolver: zodResolver(BookInput) }); current versions support Zod 4.

BookForm.tsx (with @hookform/resolvers)
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { BookInput } from "./schema";

const form = useForm<z.infer<typeof BookInput>>({ resolver: zodResolver(BookInput) });

That package isn't in the sandbox, which is a good excuse to see how little a resolver is. For a flat form it's a dozen lines: run safeParse, and on failure turn each issue into RHF's error shape, { [field]: { type, message } }. Build it:

Build itWrite a Zod resolver

Implement zodResolver(schema) in resolver.ts so the form shows the schema's messages and submits parsed values. On success, return { values: result.data, errors: {} }. On failure, return { values: {}, errors } where errors maps each field name (the issue's path joined with ".") to { type: issue.code, message: issue.message }, keeping the first issue per field.

import type { ZodType } from "zod";

export function zodResolver(schema: ZodType) {
  return async (values: Record<string, unknown>) => {
    // TODO: validate with schema.safeParse and map issues to RHF errors
    return { values, errors: {} };
  };
}

The same schema on the server#

A client-side check is a convenience, never a security boundary: anyone can send any request to your endpoint. Because the schema is plain TypeScript, the server can run the exact same BookInput.safeParse(formData) before writing to the database, and return field errors in the same shape. With React's form Actions and Server Functions, that becomes a form that works before JavaScript loads and validates on the server. That's in Server Functions, with useActionState carrying the server's errors back into the form.

Pitfalls#

Explain it out loudWhere should filter and form state live?

An interviewer asks: "A product list has filters, sorting and pagination, plus an 'add product' form. Where does each piece of state live, and why?"

Interview angle

Say it in 30 seconds

Filters, search, sorting, pagination and tabs belong in the URL: it survives refresh, it's shareable, and Back works. The URL is the single source of truth, so components derive from search params instead of copying them into state, writing with pushState for discrete changes and replaceState for typing, and always parsing params as untrusted input. Forms have their own state: values, touched, dirty, errors and submission. React Hook Form keeps inputs uncontrolled so typing doesn't re-render, with formState as a proxy subscription. A Zod schema defines the shape once for types and validation, plugs in as a resolver, and runs again on the server.

When should state live in the URL?

basic

What's the difference between pushState and replaceState, and when do you use each?

intermediate

Why is React Hook Form uncontrolled, and what does that buy you?

intermediate

What does Zod give you that TypeScript types don't?

basic

How does a schema plug into React Hook Form, and what happens on submit?

senior

If the form validates with Zod on the client, why validate again on the server?

senior

Recap#

  • URL state is state worth bookmarking, sharing and navigating: filters, search, page, tabs. The URL is the single source of truth; components derive from it and subscribe to changes.
  • pushState for discrete changes users expect Back to undo, replaceState for high-frequency ones like typing. Parse, validate and keep URLs canonical.
  • nuqs gives search params a useState-like API with typed parsers, defaults and history options, across routers.
  • React Hook Form keeps inputs uncontrolled and values in its own store, so typing doesn't re-render; formState is a proxy subscription, and Controller adapts controlled components.
  • Zod 4 defines a schema once for runtime validation and static types: safeParse, z.infer, z.flattenError. A resolver plugs it into RHF, and the same schema validates on the server.

Sources#