Sub topic 12
Initial values and resetting a form
This chapter assumes you can write a controlled input with useState, keep several fields in one state object, and handle onSubmit. It covers where a form's starting values come from and how to put the form back to that starting point.
Setting initial values
A controlled input shows whatever its state holds, so the initial value is the argument you pass to useState. For a single field, useState('') gives an empty input. For a form, define the starting object once.
import { useState } from 'react';
const initialValues = { email: '', plan: 'free', subscribe: false };
export default function SignupForm() {
const [form, setForm] = useState(initialValues);
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(initialValues);
}
return (
<form onSubmit={handleSubmit}>
<label>
Email
<input name="email" type="email" value={form.email} onChange={handleChange} />
</label>
<label>
Plan
<select name="plan" value={form.plan} onChange={handleChange}>
<option value="free">Free</option>
<option value="pro">Pro</option>
</select>
</label>
<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(initialValues)}>
Reset
</button>
</form>
);
}initialValues lives outside the component, so you can reuse it for both the first render and every reset. The change handler builds a new object with spread syntax and never mutates initialValues. That matters: if you mutated it, "reset" would restore the edited values.
The reset button has type="button". A button inside a form defaults to type="submit", so without this attribute it would submit the form.
Starting from existing data
An edit form usually starts from a record, such as a user loaded from a server. You can pass the record to useState, but useState reads its argument only on the first render. If the user prop later changes, the state keeps the old values.
The usual fix is to give the form component a key. When the key changes, React discards the old component instance and creates a new one, which runs useState again.
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} />;
}The same trick works for a reset button. Store a counter in the parent, use it as part of the key, and increment it to remount the form.
Resetting an uncontrolled form
An uncontrolled input keeps its value in the DOM. You set the starting text with defaultValue (or defaultChecked for checkboxes), and you reset with the browser's own reset() method.
export default function SearchForm() {
function handleSubmit(e) {
e.preventDefault();
const data = new FormData(e.currentTarget);
console.log('Searching for', data.get('query'));
e.currentTarget.reset();
}
return (
<form onSubmit={handleSubmit}>
<input name="query" defaultValue="react" />
<button type="submit">Search</button>
<button type="reset">Clear</button>
</form>
);
}reset() restores each field to its defaultValue, not to empty. A type="reset" button does the same without any JavaScript.
Common errors
- Using
reset()on a controlled form. The DOM changes but your state does not, so the screen and the state disagree. Reset through state instead. - Expecting
useState(props.value)to follow the prop. It does not. Use akey, or lift the state up. - Mutating the initial object. Always create a new object when updating state.
- Passing
undefinedornullasvalue. React treats the input as uncontrolled and warns when it later becomes controlled. Start from''.
Exercise
A controlled form calls e.currentTarget.reset() after a successful submit, but the typed text stays visible. Why, and what is the fix?
Show answer
The inputs are controlled, so their displayed value comes from state. reset() acts on the DOM and does not change state, so React keeps showing the state value. The fix is to call setForm(initialValues) (or the equivalent setter for each field) so the state returns to its starting values.