Sub topic 13
Using controlled components with Controller
This chapter assumes you can build a form with useForm, register, and handleSubmit, and that you have connected a Zod schema with zodResolver. You also need to know the difference between a controlled and an uncontrolled input in React.
Why register is sometimes not enough
register returns onChange, onBlur, name, and ref. React Hook Form (RHF) uses the ref to read the DOM element's value directly. This works for native inputs such as <input>, <select>, and <textarea>.
Many components do not expose a DOM element with a readable value:
- Custom widgets such as a star rating or a toggle switch.
- Component-library inputs (date pickers, comboboxes, sliders) that take
valueandonChangeprops. - Inputs whose
onChangepasses a value, not a DOM event.
Controller is RHF's adapter for these cases. It subscribes to one field in the form state and gives your component value and onChange props. Only the Controller re-renders when that field changes, not the whole form.
The Controller API
Controller needs a control object from useForm, a name, and a render function.
<Controller
control={control}
name="rating"
render={({ field, fieldState, formState }) => (
/* your component */
)}
/>The render function receives three objects:
| Object | Contents |
|---|---|
| `field` | `value`, `onChange`, `onBlur`, `name`, `ref`, `disabled` |
| `fieldState` | `invalid`, `isTouched`, `isDirty`, `error` |
| `formState` | The same state `useForm` returns, such as `errors` and `isSubmitting` |
Your component must call field.onChange(value) when the value changes and field.onBlur() when the user leaves it. RHF does not see the change otherwise. field.onChange accepts either a DOM event or a plain value, so you can pass the number, string, or object your widget produces.
A complete example
The form below has a custom star-rating component and a toggle. The schema supplies the types and the validation rules, as in earlier chapters.
import { forwardRef } from "react";
import { Controller, useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const feedbackSchema = z.object({
rating: z.number().min(1, "Choose a rating"),
subscribe: z.boolean(),
});
type FeedbackValues = z.infer<typeof feedbackSchema>;
type RatingInputProps = {
value: number;
onChange: (value: number) => void;
onBlur: () => void;
invalid?: boolean;
describedBy?: string;
};
const RatingInput = forwardRef<HTMLButtonElement, RatingInputProps>(
function RatingInput({ value, onChange, onBlur, invalid, describedBy }, ref) {
return (
<div
role="radiogroup"
aria-label="Rating"
aria-invalid={invalid}
aria-describedby={describedBy}
>
{[1, 2, 3, 4, 5].map((n) => (
<button
key={n}
type="button"
role="radio"
aria-checked={value === n}
ref={n === 1 ? ref : undefined}
onClick={() => onChange(n)}
onBlur={onBlur}
>
{n <= value ? "★" : "☆"}
</button>
))}
</div>
);
}
);
export function FeedbackForm() {
const {
control,
handleSubmit,
formState: { isSubmitting },
} = useForm<FeedbackValues>({
resolver: zodResolver(feedbackSchema),
defaultValues: { rating: 0, subscribe: false },
});
return (
<form
onSubmit={handleSubmit((values) => console.log(values))}
noValidate
>
<Controller
control={control}
name="rating"
render={({ field, fieldState }) => (
<>
<RatingInput
ref={field.ref}
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
invalid={fieldState.invalid}
describedBy={fieldState.error ? "rating-error" : undefined}
/>
{fieldState.error && (
<p id="rating-error" role="alert">
{fieldState.error.message}
</p>
)}
</>
)}
/>
<Controller
control={control}
name="subscribe"
render={({ field }) => (
<label>
<input
type="checkbox"
checked={field.value}
onChange={(e) => field.onChange(e.target.checked)}
onBlur={field.onBlur}
ref={field.ref}
/>
Send me updates
</label>
)}
/>
<button type="submit" disabled={isSubmitting}>
Send
</button>
</form>
);
}Several details in this example matter:
ref={field.ref}lets RHF focus the field when validation fails on submit. The custom component forwards the ref to its first button. Without that, focus-on-error silently does nothing for this field.defaultValuescovers every controlled field.rating: 0is a number thatmin(1)rejects, so an untouched form shows "Choose a rating".fieldState.errorreads the error for this field only. You do not need to readerrorsfrom the parent.- The checkbox passes
e.target.checked. Without that,field.valuewould become the string"on"or an event-derived value, and the schema would reject it.
The useController hook
useController does the same job as Controller but as a hook. It suits a reusable field component that takes control and name as props.
import { useController, type Control, type FieldValues, type Path } from "react-hook-form";
type TextFieldProps<T extends FieldValues> = {
control: Control<T>;
name: Path<T>;
label: string;
};
export function TextField<T extends FieldValues>({
control,
name,
label,
}: TextFieldProps<T>) {
const { field, fieldState } = useController({ control, name });
return (
<div>
<label htmlFor={name}>{label}</label>
<input
id={name}
{...field}
value={field.value ?? ""}
aria-invalid={fieldState.invalid}
/>
{fieldState.error && <p role="alert">{fieldState.error.message}</p>}
</div>
);
}Use Controller for one-off fields in a form. Use useController when you wrap the pattern in your own component.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Warning about switching from uncontrolled to controlled | The field has no default value, so `field.value` starts as `undefined` | Set `defaultValues` for every controlled field, or use `value ?? ""` |
| Schema says "Expected number, received string" | The component passes `e.target.value`, which is always a string | Convert before calling `onChange`, for example `Number(e.target.value)` |
| Value becomes `NaN` when the input is cleared | `valueAsNumber` or `Number("")` on an empty field | Store `undefined` or a string and transform in the schema (see the input versus output chapter) |
| Focus does not move to the invalid field | `field.ref` is not attached to a focusable element | Forward the ref to an element inside the component |
| `{...field}` throws a prop or ref warning | The component is a function component that does not forward refs | Wrap it in `forwardRef`, or pass props individually |
| Field validates twice or behaves oddly | The same `name` uses both `register` and `Controller` | Pick one per field |
| `rules` on `Controller` have no effect | A resolver is set, and the resolver replaces built-in `rules` | Put the rule in the Zod schema |
Performance and validation timing
A Controller re-renders when its own field's value or state changes. That is usually cheaper than lifting the value into useState, which re-renders the whole form on every keystroke.
Controlled fields follow the form's validation mode. With mode: "onBlur", validation runs when your component calls field.onBlur(). If a custom widget never calls it, that field is validated only on submit or after an onChange re-validation. Wire onBlur to the element that loses focus, not the wrapper.
Exercise
A date picker component calls onChange(date) with a Date object or null. Your Zod schema has birthday: z.date(). The form shows "Expected date, received undefined" when the user submits without touching the picker. What is the cause, and what two changes fix it?
Show answer
The field has no entry in defaultValues, so field.value and the form value start as undefined, and z.date() rejects undefined. First, decide what an empty picker means: either use z.date({ required_error: "Pick a date" }) (Zod 3) or z.date().nullable().refine((d) => d !== null, "Pick a date") with defaultValues: { birthday: null }. Second, pass field.value ?? null to the picker so it stays controlled, and call field.onChange(date) with the Date or null value it produces. The error message then comes from your schema instead of a type mismatch.
Exercise
You built a RatingInput and wrapped it in a Controller. On a failed submit, the error message appears but the keyboard focus does not move to the rating. What is missing?
Show answer
The ref from field.ref is not reaching a focusable DOM element. Wrap RatingInput in forwardRef, accept the ref, and attach it to a focusable element inside, such as the first radio button. Then pass ref={field.ref} in the render function.