Sub topic 1
How React Hook Form Manages Form State
Prerequisites
This chapter assumes you know React function components and hooks, basic TypeScript, HTML form elements, and async/await.
The form state model
React Hook Form stores form values through native, uncontrolled inputs. An uncontrolled input keeps its current value in the DOM. React Hook Form connects to that input with a ref instead of copying every keystroke into React state.
This often means fewer component re-renders. React Hook Form still tracks useful state such as errors, whether a field is dirty, and whether submission is in progress.
Registering inputs with `register`
useForm creates the form controller. Its register function connects an input to that controller. Pass the returned props to the input with a spread expression.
import { useForm } from "react-hook-form";
type ProfileValues = {
name: string;
};
export function ProfileForm() {
const {
register,
handleSubmit,
reset,
formState: { isSubmitting },
} = useForm<ProfileValues>({
defaultValues: { name: "" },
});
const onSubmit = async (values: ProfileValues) => {
await fetch("/api/profile", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
reset();
};
return (
<form onSubmit={handleSubmit(onSubmit)}>
<label htmlFor="name">Name</label>
<input id="name" {...register("name")} />
<button disabled={isSubmitting}>Save</button>
</form>
);
}Handling submission with `handleSubmit`
handleSubmit returns a submit handler for the form. It prevents the browser's default navigation, collects registered values, and calls onSubmit when validation succeeds. The callback receives an object matching ProfileValues.
Use the isSubmitting state to prevent duplicate submissions while the promise is pending.
Default values and resetting a form
defaultValues supplies the initial value for every field. Define them when creating the form, rather than relying on changing defaultValue props later.
Call reset(newValues) after loading a record or completing an operation. reset() returns the form to its configured defaults and clears tracked state.
Describing valid data with Zod schemas
Zod is a runtime validation library. A schema describes which data is valid and can reject values received from users or APIs.
import { z } from "zod";
const profileSchema = z.object({
name: z.string().min(1, "Name is required"),
});The schema does not automatically connect to React Hook Form. The connection uses a resolver, which is the subject of the form's validation setup.
Exercise
Why does React Hook Form usually avoid a React state update for every keystroke?
Show answer
It uses uncontrolled DOM inputs and refs, then updates subscribed form state only when needed.