Sub topic 1
How React Hook Form manages form state
Prerequisites
This chapter assumes you know:
- React function components and hooks
- TypeScript basics such as types and generics
- Basic HTML form elements and the submit event
- Promises and async/await
Uncontrolled inputs
A controlled input stores its value in React state. Every keystroke calls setState, and the component re-renders. React Hook Form (RHF) takes the other approach. The browser keeps each input's value in the DOM, and RHF reads it when it needs it. Inputs that work this way are called uncontrolled.
useForm creates a form store and keeps it in a ref inside your component. The store holds field values, error messages, and flags such as "touched" and "dirty". Because the store lives in a ref and not in state, changing it does not re-render the component.
What register connects
register("name") returns an object with four properties: name, onChange, onBlur, and ref. Spreading that object onto an <input> connects the element to the store. RHF uses the ref to read the element's current value and to focus it when validation fails.
import { useRef } from "react";
import { useForm } from "react-hook-form";
type Values = { name: string };
export function NameForm() {
const renders = useRef(0);
renders.current += 1;
const { register, handleSubmit } = useForm<Values>({
defaultValues: { name: "" },
});
return (
<form onSubmit={handleSubmit((values) => console.log(values.name))}>
<input {...register("name")} />
<p>Renders: {renders.current}</p>
<button type="submit">Save</button>
</form>
);
}Type in the input and the counter stays put. In development, React's Strict Mode renders components twice, so the count may start at 2.
Subscribing to state
RHF still re-renders when something you display changes. formState is a proxy, so reading formState.errors or formState.isSubmitting during render subscribes the component to that property. Properties you never read cost nothing. This is why you should read what you need from formState in the same render that uses it.
Common errors
- Not spreading the result of
register. Writingregister("name")without{...}attaches nothing, so the field is missing from the submitted values. - Adding
valueto a registered input. This turns it into a half-controlled input that fights the store. UsedefaultValuesorresetinstead. - Reading
formStateoutside render. The proxy only subscribes during render. ReadingformState.errorsinside an event handler can give stale data. - Duplicate names. Two inputs registered with the same name share one store entry, except for radio buttons and checkbox groups.
Exercise
You type in a registered input and the component does not re-render. Where is the value, and why does handleSubmit still receive it?
Show answer
The value is in the DOM input, and RHF mirrors it in a store held in a ref inside useForm. Updating a ref does not trigger a render. On submit, handleSubmit reads the store (and the input refs), so it has the current values.