Sub topic 4
Default values and resetting a form
This chapter assumes you can write React function components with hooks, read basic TypeScript generics, and have seen register and handleSubmit. It covers how React Hook Form (RHF) stores starting values, and how reset returns a form to a known state.
Why default values matter
RHF reads input values from the DOM, so it needs a baseline to compare against. The defaultValues option of useForm supplies that baseline. It does three jobs:
- It fills each registered input when the form first renders.
- It defines what "unchanged" means for
formState.isDirtyandformState.dirtyFields. - It is the state a later
reset()call returns to.
Always provide a value for every field. If you omit one, the field starts as undefined, and a text input then switches from uncontrolled to controlled behavior or fails a string schema with a confusing "Required" message. For text inputs, use an empty string.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const profileSchema = z.object({
name: z.string().min(1, "Name is required"),
newsletter: z.boolean(),
});
type ProfileValues = z.infer<typeof profileSchema>;
export function ProfileForm() {
const {
register,
handleSubmit,
reset,
formState: { errors, isDirty },
} = useForm<ProfileValues>({
resolver: zodResolver(profileSchema),
defaultValues: { name: "", newsletter: false },
});
const onSubmit = (values: ProfileValues) => {
console.log(values);
reset(values); // the saved values become the new baseline
};
return (
<form onSubmit={handleSubmit(onSubmit)} noValidate>
<label htmlFor="name">Name</label>
<input id="name" {...register("name")} />
{errors.name && <p role="alert">{errors.name.message}</p>}
<label>
<input type="checkbox" {...register("newsletter")} />
Subscribe
</label>
<button type="submit" disabled={!isDirty}>
Save
</button>
<button type="button" onClick={() => reset()}>
Discard changes
</button>
</form>
);
}What reset does
Calling reset() with no arguments restores every input to its default value. It also clears errors, the dirty state, and the touched state. Calling reset(values) does the same, but it treats values as the new defaults. That is why the example calls reset(values) after saving: isDirty becomes false and "Discard changes" now returns to the saved data.
The following diagram shows the flow.
Loading data from an API
Data fetched after the first render is not available when useForm runs. Do not pass it to defaultValues later, because RHF reads that option only once. Use one of these approaches instead:
- Call
reset(data)inside an effect once the data arrives. - Pass an async function as
defaultValues. RHF waits for it and setsformState.isLoadingwhile it runs. - Use the
valuesoption, which keeps the form synchronized with an external value.
useEffect(() => {
if (user) reset({ name: user.name, newsletter: user.newsletter });
}, [user, reset]);Common errors
- Empty defaults for numbers or dates. An input always yields a string, so a default of
0against a string schema fails. Match the schema's input type. - Mutating defaults. Pass a fresh object. RHF clones it, but sharing a mutable constant across forms invites bugs.
- Expecting
defaultValuesto update on re-render. It will not. Useresetorvalues.
Exercise
A user opens an edit form, and the data arrives from the API after the first render. You passed the data to defaultValues on each render, but the inputs stay empty. Why, and how do you fix it?
Show answer
RHF reads defaultValues only on the first render, so later changes are ignored. Call reset(data) in an effect when the data arrives, or use the values option or an async defaultValues function.