The Key Prop Resets State by Changing Identity
You'll learn how to intentionally reset a component's state by changing its key prop.
The Core Idea
React uses a component's position in the tree to track its identity and preserve its state across re-renders. But there's a secret override: the key prop. When you change a component's key, React thinks "this is a completely different component now" — it unmounts the old instance (destroying its state) and mounts a brand new instance with fresh initial state.
Why This Matters
Sometimes you want to reset state. Imagine a form that appears for different users — keeping the old user's input when switching users would be a bug. Changing the key gives you a clean slate without manually calling multiple setState functions.
The Mental Model
Think of key as a component's "identity card." If the ID number changes, React treats it as a different person entirely. The old person leaves (unmount), and a new person arrives (mount) with their own fresh state.
// When userID changes, React sees a NEW ProfileForm, not an update
<ProfileForm key={userID} />
Every time userID changes values (123 → 456), React:
- Unmounts the old
ProfileForm(state destroyed) - Mounts a fresh
ProfileForm(initial state restored)
This works for any state inside ProfileForm — counters, text inputs, toggles — everything resets automatically.
When to Use This Pattern
Use key to reset state when switching between logically different items (different users, different products, different questions in a quiz). Don't use it as a shortcut for regular state updates within the same item.
Key Takeaway: Changing a component's key forces React to unmount and remount it with completely fresh state — a powerful tool for intentional resets.