Keys and Component State
What you'll learn: How changing a component's key forces React to unmount the old instance and mount a new one, wiping out all its internal state.
The Key as Identity
Remember that keys help React track which component is which across renders. But here's the powerful consequence: when a key changes, React treats it as a completely different component.
Think of keys like name tags at a conference. If someone's name tag changes from "Alice" to "Bob," you're not looking at the same person anymore — you're looking at a different attendee entirely.
Forcing a Reset
When you change an element's key:
- React unmounts the old component instance (runs cleanup, discards state)
- React mounts a fresh component instance with the new key (runs initialization, creates new state)
This is incredibly useful when you need to reset component state. Instead of manually clearing variables or triggering complex logic, you simply change the key.
Practical Example Pattern
// Without key change: input keeps its value when user changes
<TextInput userId={currentUser} />
// With key change: input clears when userId changes
<TextInput key={currentUser} userId={currentUser} />
When currentUser changes from 5 to 7, the key changes too. React destroys the old TextInput (losing any typed characters, internal state, etc.) and creates a brand new one.
When This Matters
Use this pattern when a component's state should "belong" to a particular entity. Form fields for different users, video players for different videos, or timers for different games all benefit from key-based resets.
Key Takeaway: Changing a component's key forces React to unmount the old instance and mount a completely fresh one, automatically resetting all state — a simple but powerful reset mechanism.