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).handleSubmitvalidates first and only callsonSubmitwith 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 state | Server state | |
|---|---|---|
| Examples | Is the menu open? Form drafts, selected tab, theme | Products, orders, the current user's profile |
| Owned by | The browser | The server; the browser holds a copy |
| Problems | Sharing between components | Caching, stale data, loading and error states, refetching, duplicate requests, pagination |
| Tools | useState, useReducer, context, Zustand, Redux | TanStack 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
| Library | Style | Notes |
|---|---|---|
| Zustand | A small store with hooks; components subscribe to only the parts they use | Very little boilerplate; popular for modern apps |
| Redux Toolkit | A single store, reducers ("slices") and actions; strong DevTools | Common in large and older codebases; RTK Query handles server state |
| Jotai / Recoil-style atoms | Many small independent pieces of state | Fine-grained updates |
| Context + useReducer | Built in | Enough 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:
- Local state (
useState). - Lift state up and use composition (Lesson 165).
- Put shareable UI state in the URL.
- Use a server-state library for API data.
- Add context for a few global values.
- 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
| Word | Meaning |
|---|---|
| Form library | A library that manages form values, validation and submission |
| Resolver | Connects a validation schema to a form library |
| Client state | State that exists only in the browser |
| Server state | A browser copy of data owned by the server |
| TanStack Query | A library for fetching and caching server state |
| Global store | Shared state accessible from any component |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.