Change the Key to Wipe State Clean
Keys as a Reset
Changing a component's `key` makes React unmount the old instance and mount a new one — wiping all its state.
What you'll learn
- Use a key to reset internal state
- Recognize the pattern in forms and routes
React uses key to identify a component instance. Change the key,
and React thinks “different component now” — it unmounts the old
one and mounts a fresh one. All internal state goes with it.
This sounds obscure but is a surprisingly useful trick.
The Scenario
A profile editor that’s reused for different users:
function ProfileEditor({ userId }) {
const [name, setName] = useState("");
const [bio, setBio] = useState("");
// when userId changes, name/bio still hold the OLD user's data
// until the form is somehow reset.
return <form>{/* ... */}</form>;
} You could useEffect to reset state when userId changes — but
that’s two renders and an effect to keep in sync.
The Fix
Give the editor a key={userId}. When userId changes, React
mounts a new component, and state resets automatically:
function ProfilePage({ userId }) {
return <ProfileEditor key={userId} userId={userId} />;
} That’s it. No effect, no manual reset.
When It Helps
- Forms that switch between editing different records
- Modals that should “start fresh” each time
- Tabs whose content should reset when the user switches
When It’s Too Heavy
Remounting throws away all the work the component did to render (child effects, refs, animations). For frequent changes that should only reset some state, prefer an effect or controlled state from the parent.
Pairing With Forms
const [editingUser, setEditingUser] = useState(null);
return (
<>
<Picker onPick={setEditingUser} />
{editingUser && (
<UserForm key={editingUser.id} user={editingUser} />
)}
</>
); Selecting a different user resets the form to that user’s values — and clears any in-progress edits.
Up Next
A taste of React Server Components — the newer rendering paradigm.
Server Components Intro →