Sub topic 4
Default Values and Resetting a Form
This chapter covers how defaultValues works in React Hook Form, how reset changes it, and the mistakes that follow from misunderstanding either. It assumes you know React function components and hooks, TypeScript generics, and the basics of register and handleSubmit. It also assumes you have seen a Zod schema passed to zodResolver.
Why default values matter
React Hook Form (RHF) uses uncontrolled inputs. The DOM holds the live value of each input, and RHF reads it through a ref. Because of this, RHF needs to know what each field should contain at the start. That starting state is the defaultValues option of useForm.
Default values do four jobs:
- They set the initial value shown in each registered input.
- They define the baseline for
isDirtyanddirtyFields. A field is dirty when its current value differs from its default. - They define the values
reset()returns to when you call it with no arguments. - They give TypeScript and RHF the shape of the form, which helps path autocompletion.
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";
const profileSchema = z.object({
displayName: z.string().min(1, "Name is required"),
newsletter: z.boolean(),
role: z.enum(["reader", "editor"]),
});
type ProfileValues = z.infer<typeof profileSchema>;
export function ProfileForm() {
const {
register,
handleSubmit,
reset,
formState: { errors, isDirty },
} = useForm<ProfileValues>({
resolver: zodResolver(profileSchema),
defaultValues: {
displayName: "",
newsletter: false,
role: "reader",
},
});
return (
<form onSubmit={handleSubmit((values) => console.log(values))} noValidate>
<label htmlFor="displayName">Display name</label>
<input id="displayName" {...register("displayName")} />
{errors.displayName && <p role="alert">{errors.displayName.message}</p>}
<label>
<input type="checkbox" {...register("newsletter")} />
Send me the newsletter
</label>
<label htmlFor="role">Role</label>
<select id="role" {...register("role")}>
<option value="reader">Reader</option>
<option value="editor">Editor</option>
</select>
<button type="submit">Save</button>
<button type="button" onClick={() => reset()} disabled={!isDirty}>
Discard changes
</button>
</form>
);
}The Discard button calls reset() with no arguments, so the form returns to the values given in useForm. Reading isDirty from formState subscribes the component to that value, so it re-renders when dirtiness changes.
Always provide defaults for every field
Pass a default for every field, even empty ones. Use "" for text inputs, false for checkboxes, and a real option for selects.
If you omit a default, the field starts as undefined. This causes three problems:
- RHF cannot compare against a baseline, so dirty tracking is less reliable.
- A text input registered without a default may be
undefinedin the submitted values until the user types, so the Zod schema sees a missing key instead of an empty string. Az.string().min(1, "Required")rule then reports the default Zod "expected string, received undefined" message instead of your custom one. - Array and nested fields have no shape for
useFieldArrayand nested paths to build on.
Empty strings are the right default for text. Using undefined for a text field makes the input uncontrolled in a way React may warn about when you later pass a value, and it hides the empty state from your schema.
Defaults are read once
defaultValues is cached on the first render. If you change the object on a later render, nothing happens. This is the most common source of confusion.
// Wrong: user is undefined on the first render, so the form caches empty defaults.
const { data: user } = useUser();
const form = useForm<ProfileValues>({
defaultValues: { displayName: user?.name ?? "", newsletter: false, role: "reader" },
});When user arrives, the form does not update. You have two ways to fix this.
Option 1: call reset when data arrives
import { useEffect } from "react";
const { data: user } = useUser();
const { register, handleSubmit, reset } = useForm<ProfileValues>({
resolver: zodResolver(profileSchema),
defaultValues: { displayName: "", newsletter: false, role: "reader" },
});
useEffect(() => {
if (user) {
reset({
displayName: user.name,
newsletter: user.newsletter,
role: user.role,
});
}
}, [user, reset]);reset(values) replaces both the current field values and the stored defaults. After this call, isDirty is false and the new values are the baseline.
Option 2: pass an async function
defaultValues also accepts a function that returns a promise. RHF calls it once and fills the form when it resolves.
const { register, formState } = useForm<ProfileValues>({
resolver: zodResolver(profileSchema),
defaultValues: async () => {
const response = await fetch("/api/profile");
return (await response.json()) as ProfileValues;
},
});
if (formState.isLoading) {
return <p>Loading…</p>;
}While the promise is pending, formState.isLoading is true. The function's return value is not validated by the schema, so parse it if you do not trust the API.
Another approach is to load the data in a parent component and render the form only once the data exists. The form then mounts with real defaults on its first render, and neither a reset nor an async function is needed. Use a key prop on the form to remount it when the record identity changes.
export function ProfilePage({ userId }: { userId: string }) {
const { data: user } = useUser(userId);
if (!user) return <p>Loading…</p>;
return <ProfileForm key={user.id} user={user} />;
}What reset does
reset accepts optional values and optional options.
| Call | Field values after | Stored defaults after |
|---|---|---|
| `reset()` | Original defaults | Unchanged |
| `reset(values)` | `values` | Replaced by `values` |
| `reset(values, { keepDefaultValues: true })` | `values` | Unchanged |
| `reset(undefined, { keepValues: true })` | Current values | Unchanged, but dirty state clears relative to them |
The options object lets you keep parts of the form state:
keepErrorskeeps current validation errors.keepDirtykeeps the dirty flags.keepTouchedkeeps the touched flags.keepIsSubmittedandkeepSubmitCountkeep submission history.keepValueskeeps current field values while resetting the rest.keepDefaultValueskeeps the original defaults rather than replacing them.
Resetting after a successful submission
A common pattern is clearing the form after a save. Do this inside useEffect on isSubmitSuccessful, or directly after the awaited request.
const onSubmit = async (values: ProfileValues) => {
await fetch("/api/profile", {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(values),
});
reset(values);
};Calling reset(values) here makes the saved values the new baseline. The form is no longer dirty, and a later Discard goes back to what was just saved, not to the old defaults. To clear the form to empty instead, call reset() with no arguments.
Do not call reset during render. It updates state and causes an infinite loop. Call it from an event handler, an effect, or after an await.
Defaults and the schema
Defaults should satisfy the schema's input type. If your schema transforms values, the defaults use the input side. A schema with .transform(Number) on a string field needs a string default such as "1", as in the transform chapter. Typing useForm<z.input<typeof schema>, unknown, z.output<typeof schema>> makes TypeScript check this for you.
Defaults are not validated when the form loads. An empty displayName default is fine even though the schema rejects it, because validation runs only on the configured mode (submit by default). The user sees an error only after trying to submit.
Common errors
- Form stays empty after data loads. The default was read on the first render. Call
reset(data)or use an asyncdefaultValues. - Reset puts old data back. You called
reset()after data loaded but never passed the loaded data toreset, so the original empty defaults came back. Pass the data. - A checkbox or select shows the wrong value. The default type does not match the control. Use a boolean for a single checkbox and a string that matches an option for a select.
isDirtyis always true or always false. ReadingisDirtyin render is required for the subscription. Also check that defaults exist for all fields.- Array rows come back after reset.
useFieldArrayfollows the form's values, soreset(values)with the rightitemsarray is the way to change rows.
Exercise
A profile form calls useForm with defaultValues { displayName: user?.name ?? "" } while the user query is still loading. After the query finishes, the input stays empty. Why, and give two fixes.
Show answer
RHF reads defaultValues once, on the first render, when user is undefined, so later changes to the object are ignored. Fix 1: call reset({ displayName: user.name }) in a useEffect when user becomes available. Fix 2: render the form only after the user has loaded (optionally with key={user.id}), or pass an async function as defaultValues and use formState.isLoading.
Exercise
After a successful save you call reset(values) rather than reset(). What is the difference for isDirty and for a later "Discard changes" button?
Show answer
reset(values) replaces both the current values and the stored defaults with the saved values, so isDirty becomes false and a later Discard returns to the saved values. reset() would return to the original defaults from useForm, discarding what was just saved.