Skip to the content

Lesson 174 of 296

Forms, validation and state libraries

What you will learn

  • Form libraries and why teams use them
  • React Hook Form with Zod
  • Client state vs server state
  • Data-fetching libraries: TanStack Query
  • Global state libraries: Zustand and Redux Toolkit
  • When you do not need any of them
On this page

Why form libraries?

Real forms need: validation rules, error messages per field, touched and dirty tracking, submission state, server errors, and good performance. Writing this by hand for every form is repetitive. React Hook Form is the most popular library: it uses uncontrolled inputs (Lesson 164) for performance and works with Zod schemas (Lesson 114) so validation and types come from one place.

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

const SignupSchema = z.object({
  name: z.string().min(1, "Enter your name"),
  email: z.email("Enter a valid email address"),
  password: z.string().min(8, "Use at least 8 characters")
});
type SignupValues = z.infer<typeof SignupSchema>;

function SignupForm() {
  const {
    register,
    handleSubmit,
    formState: { errors, isSubmitting }
  } = useForm<SignupValues>({ resolver: zodResolver(SignupSchema) });

  async function onSubmit(values: SignupValues) {
    await fetch("/api/signup", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(values)
    });
  }

  return (
    <form onSubmit={handleSubmit(onSubmit)} noValidate>
      <label htmlFor="name">Name</label>
      <input id="name" {...register("name")} aria-invalid={!!errors.name} />
      {errors.name && <p role="alert">{errors.name.message}</p>}

      <label htmlFor="email">Email</label>
      <input id="email" type="email" {...register("email")} aria-invalid={!!errors.email} />
      {errors.email && <p role="alert">{errors.email.message}</p>}

      <label htmlFor="password">Password</label>
      <input id="password" type="password" {...register("password")} />
      {errors.password && <p role="alert">{errors.password.message}</p>}

      <button type="submit" disabled={isSubmitting}>Create account</button>
    </form>
  );
}
  • register("email") connects an input (name, ref, change handler).
  • handleSubmit validates first and only calls onSubmit with typed, valid values.
  • The same Zod schema can validate the request on the server (Parts 15 and 16), so rules never drift apart. Remember: client validation is for comfort, server validation is for security (Lesson 11).

Client state vs server state

A very useful distinction in React interviews:

Client stateServer state
ExamplesIs the menu open? Form drafts, selected tab, themeProducts, orders, the current user's profile
Owned byThe browserThe server; the browser holds a copy
ProblemsSharing between componentsCaching, stale data, loading and error states, refetching, duplicate requests, pagination
ToolsuseState, useReducer, context, Zustand, ReduxTanStack Query, SWR, RTK Query, server components

Putting server data into a global store by hand (fetch in an effect, save in Redux) is a common source of complexity. A server-state library handles it.

TanStack Query

const { data, isPending, error } = useQuery({
  queryKey: ["orders", page],
  queryFn: () => fetchJson(`/api/orders?page=${page}`, OrdersSchema)
});

It provides caching by key, de-duplication of identical requests, background refetching, retries, pagination helpers, and useMutation for changes with cache updates or optimistic updates. In Next.js apps, server components (Part 13) often fetch data directly instead.

Global client state libraries

LibraryStyleNotes
ZustandA small store with hooks; components subscribe to only the parts they useVery little boilerplate; popular for modern apps
Redux ToolkitA single store, reducers ("slices") and actions; strong DevToolsCommon in large and older codebases; RTK Query handles server state
Jotai / Recoil-style atomsMany small independent pieces of stateFine-grained updates
Context + useReducerBuilt inEnough for many small and medium apps (Lesson 169)

Zustand example:

import { create } from "zustand";

type CartStore = {
  count: number;
  add: () => void;
};

const useCartStore = create<CartStore>((set) => ({
  count: 0,
  add: () => set((s) => ({ count: s.count + 1 }))
}));

function CartBadge() {
  const count = useCartStore((s) => s.count);
  return <span>{count}</span>;
}

The selector ((s) => s.count) means CartBadge only re-renders when count changes.

When you do not need a state library

Start simple:

  1. Local state (useState).
  2. Lift state up and use composition (Lesson 165).
  3. Put shareable UI state in the URL.
  4. Use a server-state library for API data.
  5. Add context for a few global values.
  6. Add a global store only when many distant components share frequently changing client state.

Interviewers like candidates who choose the simplest tool that works and can explain the trade-off.

How to say it in an interview

"For forms I use React Hook Form with a Zod resolver, so validation and types come from one schema that I can reuse on the server. I separate client state, like UI toggles, from server state, which is a cached copy of server data with its own problems of caching, staleness and refetching, handled by TanStack Query or server components. For shared client state I start with local state, lifting state, the URL and context, and only add Zustand or Redux Toolkit when many distant components share frequently changing state."

Key words

WordMeaning
Form libraryA library that manages form values, validation and submission
ResolverConnects a validation schema to a form library
Client stateState that exists only in the browser
Server stateA browser copy of data owned by the server
TanStack QueryA library for fetching and caching server state
Global storeShared state accessible from any component

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.