Sub topic 1
How React Hook Form manages form state
This chapter explains the working model behind React Hook Form (RHF). You will see why it uses uncontrolled inputs and refs, what lives where, and which mistakes follow from that model. Later chapters build on it with register, handleSubmit, and Zod.
Prerequisites
This chapter assumes you know:
- React function components and hooks such as
useStateanduseRef. - TypeScript basics, including types and generics.
- Basic HTML form elements and the submit event.
- Promises and
async/await.
You do not need to know Zod yet. It appears in later chapters.
The problem RHF solves
The usual way to build a React form is with controlled inputs. Each input's value lives in React state, and every keystroke calls a state setter.
import { useState } from "react";
export function ControlledForm() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
return (
<form
onSubmit={(event) => {
event.preventDefault();
console.log({ email, password });
}}
>
<input value={email} onChange={(e) => setEmail(e.target.value)} />
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
/>
<button type="submit">Send</button>
</form>
);
}This works, but each keystroke re-renders the whole component, and every field needs its own state, handler, and error logic. With 30 fields, the cost in code and renders adds up.
Uncontrolled inputs and refs
An uncontrolled input keeps its own value in the browser's DOM. React does not own it. You read the value when you need it, through a ref (a reference to the underlying DOM element).
RHF is built on this idea. It attaches a ref to each input and reads ref.current.value at the moments that matter, such as on submit or on blur. Typing in a field does not cause React to re-render the form component.
The result is a different split of responsibilities:
| Concern | Controlled form | React Hook Form |
|---|---|---|
| Where the value lives | React state | The DOM input, tracked through a ref |
| Re-render on each keystroke | Yes | No, unless you subscribe to the value |
| Per-field boilerplate | State, handler, error | One `register` call |
| Reading all values | Combine your state variables | RHF collects them from refs |
What `useForm` gives you
You call useForm once per form. It returns an object of methods and state. These are the ones that matter for this chapter.
| Member | Purpose |
|---|---|
| `register` | Connects an input to the form and returns the props it needs |
| `handleSubmit` | Wraps your submit handler, validates first, then calls it with the values |
| `formState` | Holds `errors`, `isSubmitting`, `isDirty`, `isValid`, and more |
| `control` | An object that child hooks and components use to reach the form |
| `watch` | Subscribes to field values and re-renders when they change |
| `getValues` | Reads current values once, with no subscription |
| `setValue`, `reset`, `setError` | Update values and errors from code |
The next chapters cover register and handleSubmit in detail. Here, the important point is where the state is kept.
State lives in a ref, not in React state
useForm stores field values, validation results, and metadata in an internal object that persists across renders. This object is not React state, so changing it does not trigger a render by itself. RHF triggers a render only when a part of the state that your component has read changes.
Subscribing to form state through a proxy
formState is a Proxy. When you read formState.errors or formState.isDirty during render, RHF records that you need that piece of state. It then re-renders your component only when that piece changes.
import { useForm } from "react-hook-form";
type Values = { name: string };
export function SubscribedForm() {
const {
register,
handleSubmit,
formState: { errors },
} = useForm<Values>({ defaultValues: { name: "" } });
return (
<form onSubmit={handleSubmit((values) => console.log(values))}>
<input {...register("name", { required: "Name is required" })} />
{errors.name && <p role="alert">{errors.name.message}</p>}
<button type="submit">Save</button>
</form>
);
}This component reads errors, so it re-renders when errors change. It does not read isDirty, so changes to dirtiness do not cause renders.
The following diagram shows the flow of data.
Common errors from the proxy model
Because formState tracks reads, a few mistakes come up often.
- Reading
formStateproperties only inside an effect or handler. The subscription is set up during render. If you first readformState.isDirtyin a callback, the value may not update as you expect. Read the property in the render body, ideally by destructuring. - Expecting
watchto be free.watch("email")subscribes the whole component to that field. Each keystroke re-renders it. UsegetValueswhen you only need the value inside a handler. - Expecting live values from
getValuesin JSX. It reads once and does not subscribe, so the displayed text will not update as the user types. - Using
useStatealongside RHF for the same field. You then have two sources of truth, and they drift apart.
The mode and refs on custom components
RHF needs a real DOM element behind each register call. The props it returns are name, onChange, onBlur, and ref. If you spread them onto a custom component, that component must forward the ref to an underlying input. Otherwise RHF cannot read the value, and the field will look empty on submit.
import { forwardRef, type InputHTMLAttributes } from "react";
export const TextField = forwardRef<
HTMLInputElement,
InputHTMLAttributes<HTMLInputElement>
>(function TextField(props, ref) {
return <input ref={ref} {...props} />;
});In React 19, ref is a normal prop for function components, so forwardRef is no longer required there. On React 18 and earlier, you still need it.
When values are read
RHF collects values at specific events, not on every keystroke. By default:
- Validation runs on submit. After a failed submit, it re-validates on change.
handleSubmitreads all registered values at that time.- Fields that unmount keep their values by default, unless you set
shouldUnregister: true.
The shouldUnregister option changes the last point. With true, an unmounted field is removed from the values and from validation. This is useful for conditional fields, but it also means the data disappears when the input leaves the screen.
A worked example
This example shows how little React state is involved. It logs a render count, so you can see how often the component re-renders while you type.
import { useRef } from "react";
import { useForm } from "react-hook-form";
type Values = { firstName: string; lastName: string };
export function RenderCountForm() {
const renders = useRef(0);
renders.current += 1;
const { register, handleSubmit } = useForm<Values>({
defaultValues: { firstName: "", lastName: "" },
});
return (
<form onSubmit={handleSubmit((values) => console.log(values))}>
<p>Renders: {renders.current}</p>
<input {...register("firstName")} placeholder="First name" />
<input {...register("lastName")} placeholder="Last name" />
<button type="submit">Submit</button>
</form>
);
}Type in both fields. The render count stays at its initial value, because the component reads no formState and calls no watch. In development with React Strict Mode, the count starts higher because React renders twice on purpose. Now add const firstName = watch("firstName") after useForm, and the counter climbs with each keystroke.
Trade-offs
- Fewer renders, but values are less visible. You cannot just print a state variable. You must opt in with
watchoruseWatch. - DOM-first, so tests and custom components need care. Components must expose a ref, and tests need to interact with real inputs.
- Two ways to read values.
watchis reactive andgetValuesis a snapshot. Choose by whether the UI must update.
Exercise
A component calls const { register, watch } = useForm() and renders <p>{watch("email")}</p> next to an input registered as email. Why does this component re-render on every keystroke, and how would you read the email without that cost inside a submit-time helper?
Show answer
watch("email") subscribes the component to that field, so RHF re-renders it whenever the value changes. If you only need the value at a single moment, such as inside a click handler or submit helper, call getValues("email"). It reads the current value from RHF's internal store without subscribing, so no extra renders happen.
Exercise
You wrap a design-system <Input> component, spread {...register("name")} on it, and the submitted name is always empty. What is the most likely cause?
Show answer
The component does not forward the ref that register returns to its underlying <input>. RHF cannot reach the DOM element to read its value. Fix it by using forwardRef (React 18 and earlier) or by passing ref through as a prop (React 19), or by using Controller for components that cannot expose a ref.