Sub topic 12
Initial values and resetting a form
This chapter assumes you know useState, controlled inputs, a single state object for many fields, and onSubmit with preventDefault. It covers how a form gets its starting values, how to return it to those values, and how to load different records into the same form without stale data.
Where initial values come from
A controlled input shows whatever its state holds. The initial value is the argument you pass to useState. React reads that argument only on the first render of a component instance. Later renders ignore it.
Most forms start from one of two sources:
- Constants, such as an empty string or a default plan.
- Props, such as an existing user record that the form edits.
Define the starting values once, outside the component or in a function, so that reset logic can reuse them.
import { useState } from 'react';
const EMPTY_FORM = {
email: '',
plan: 'free',
subscribe: false,
};
export default function SignupForm() {
const [form, setForm] = useState(EMPTY_FORM);
function handleChange(e) {
const { name, type, value, checked } = e.target;
setForm((prev) => ({
...prev,
[name]: type === 'checkbox' ? checked : value,
}));
}
return (
<form>
<input name="email" value={form.email} onChange={handleChange} />
<p>Plan: {form.plan}</p>
</form>
);
}Because EMPTY_FORM is a module-level constant, it is created once. Your update code never mutates it, because setForm builds a new object with spread syntax.
Never start a controlled input as undefined
If a value can be undefined or null, React treats the input as uncontrolled. When the value later becomes a string, React warns that the component is changing an uncontrolled input to be controlled.
This commonly happens when you load data from a server and the fields are missing at first. Give every field a defined default and normalize incoming data:
const initial = {
name: user?.name ?? '',
bio: user?.bio ?? '',
};Use ?? rather than ||. With ||, a legitimate falsy value such as 0 for a number field would be replaced by the fallback.
Initial values for uncontrolled inputs
An uncontrolled input holds its own value in the DOM. You set its starting text with defaultValue, or defaultChecked for checkboxes and radios.
export default function SearchForm() {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
console.log('Searching for', data.get('query'));
}
return (
<form onSubmit={handleSubmit}>
<input name="query" defaultValue="react" />
<label>
<input name="exact" type="checkbox" defaultChecked />
Exact match
</label>
<button type="submit">Search</button>
</form>
);
}defaultValue sets the value once. Changing it in a later render does not change what the input shows. That behavior is the same as the useState argument, and it leads to the same problem described below.
Resetting a controlled form
For a controlled form, resetting means setting the state back to the initial values. React then re-renders and every input shows the starting value again.
import { useState } from 'react';
const EMPTY_FORM = { email: '', plan: 'free', subscribe: false };
export default function SignupForm() {
const [form, setForm] = useState(EMPTY_FORM);
function handleChange(e) {
const { name, type, value, checked } = e.target;
setForm((prev) => ({
...prev,
[name]: type === 'checkbox' ? checked : value,
}));
}
function handleSubmit(e) {
e.preventDefault();
console.log('Submitting', form);
setForm(EMPTY_FORM);
}
return (
<form onSubmit={handleSubmit}>
<input name="email" value={form.email} onChange={handleChange} />
<select name="plan" value={form.plan} onChange={handleChange}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
<label>
<input
name="subscribe"
type="checkbox"
checked={form.subscribe}
onChange={handleChange}
/>
Send me updates
</label>
<button type="submit">Sign up</button>
<button type="button" onClick={() => setForm(EMPTY_FORM)}>
Reset
</button>
</form>
);
}Note the Reset button has type="button". Inside a form, a button without a type is a submit button, so clicking it would submit the form.
If you also keep errors or touched flags in state, reset them too. Otherwise old error messages stay on screen after the values are cleared.
function resetAll() {
setForm(EMPTY_FORM);
setErrors({});
setTouched({});
}Why not use a native reset button?
HTML has <button type="reset"> and form.reset(). They restore each DOM input to its defaultValue. This works for uncontrolled inputs. For controlled inputs it is a trap: the DOM changes, but React state does not, so the next render can put the old values back, or the display and state disagree. Use setState for controlled forms and native reset for uncontrolled ones.
| Form style | How to reset | Why |
|---|---|---|
| Controlled | Set state back to initial values | State is the source of truth |
| Uncontrolled | `e.currentTarget.reset()` or `type="reset"` | The DOM holds the values |
| Either | Change the `key` of the form component | React creates a fresh instance |
Resetting an uncontrolled form
export default function NoteForm() {
function handleSubmit(e) {
e.preventDefault();
const form = e.currentTarget;
const data = new FormData(form);
console.log('Saved', data.get('note'));
form.reset();
}
return (
<form onSubmit={handleSubmit}>
<textarea name="note" defaultValue="" />
<button type="submit">Save</button>
</form>
);
}Save the form reference in a variable before any await. In the code above that is not needed, but if you add an asynchronous step, read e.currentTarget first, because it is only reliable while the handler runs synchronously.
The stale initial state problem
Suppose a form edits a user and receives the user as a prop. You write useState(user.name). The user changes from Ada to Grace, the component re-renders with new props, and the input still shows Ada. React ignores the useState argument after the first render.
A tempting fix is an effect that copies props into state:
useEffect(() => {
setName(user.name);
}, [user]);This works, but it renders once with stale data and then again with the right data. It also overwrites anything the user has typed whenever the prop object changes, even if the id is the same.
Reset with a key
The cleaner fix is to give the form a key tied to the record. When the key changes, React discards the old component instance and creates a new one, which runs useState again with the new props.
import { useState } from 'react';
function ProfileForm({ user }) {
const [name, setName] = useState(user.name);
return (
<input value={name} onChange={(e) => setName(e.target.value)} />
);
}
export default function ProfilePage({ user }) {
return <ProfileForm key={user.id} user={user} />;
}Switching from user 1 to user 2 remounts ProfileForm with fresh state. Using key also resets everything inside the component, including errors and touched flags, with no extra code.
The same technique gives you a "Reset" button for a whole form. Keep a counter in the parent and use it in the key:
import { useState } from 'react';
function Editor({ initial, onReset }) {
const [text, setText] = useState(initial);
return (
<div>
<textarea value={text} onChange={(e) => setText(e.target.value)} />
<button type="button" onClick={onReset}>Discard changes</button>
</div>
);
}
export default function EditorPage() {
const [version, setVersion] = useState(0);
return (
<Editor
key={version}
initial="Original text"
onReset={() => setVersion((v) => v + 1)}
/>
);
}Dirty tracking: has the form changed?
Edit forms often need to know whether the user has changed anything, for example to disable a Save button or warn before leaving. Keep the original values and compare them with the current ones.
import { useState } from 'react';
function ProfileForm({ user }) {
const [form, setForm] = useState({ name: user.name, bio: user.bio });
const isDirty =
form.name !== user.name || form.bio !== user.bio;
function handleChange(e) {
setForm((prev) => ({ ...prev, [e.target.name]: e.target.value }));
}
return (
<form>
<input name="name" value={form.name} onChange={handleChange} />
<textarea name="bio" value={form.bio} onChange={handleChange} />
<button type="button" onClick={() => setForm({ name: user.name, bio: user.bio })}>
Undo changes
</button>
<button type="submit" disabled={!isDirty}>Save</button>
</form>
);
}isDirty is derived during render. It is not stored in state, so it cannot get out of sync with the values.
Common mistakes
- Mutating the initial object. Writing
form.email = ''and callingsetForm(form)does nothing, because React sees the same object reference. Always pass a new object. - Resetting after an async call fails. If you clear the form before the server confirms, the user loses their input on error. Reset in the success branch only.
- Forgetting nested state. Resetting
formbut noterrors,touched, or asubmittingflag leaves the interface inconsistent. - Using
defaultValueon a controlled input. Pass eithervaluewithonChange, ordefaultValue. Passing both triggers a warning. - Sharing a mutable initial object. If the initial state contains arrays or nested objects and you mutate them in place, the "initial" constant changes too. Update immutably.
Choosing a reset approach
- If the inputs are uncontrolled, call
form.reset()and setdefaultValuefor the starting text. - If the inputs are controlled and the same record stays on screen, set state back to the initial object, and clear errors and touched flags.
- If the form shows a different record, or "discard everything" is the goal, change the
key. - If you need to compare current and original values, derive
isDirtyduring render.
Exercise
A ProfileForm component uses useState(user.name). When the parent passes a different user, the input still shows the previous name. Why does this happen, and what is the simplest fix that also clears any error state inside the form?
Show answer
React uses the argument to useState only on the first render of a component instance, so later prop changes do not update the state. The simplest fix is to render the form with key={user.id} in the parent. A new key makes React unmount the old instance and mount a new one, which runs useState with the new user and resets all other state in the component, including errors.
Exercise
Your controlled signup form has a Reset button inside the form. Clicking it submits the form instead of clearing it, and when you switch to type="reset" the inputs seem to clear but React still holds the old values. What are the two problems and their fixes?
Show answer
First, a <button> without a type inside a form is a submit button, so the plain Reset button needs type="button". Second, a native reset button changes only the DOM values, not React state, so it does not work reliably with controlled inputs. Use type="button" with an onClick that calls setForm with the initial values, and clear the errors and touched state too.