The Consequences of Changing Keys Mid-Lifecycle
You'll learn: What happens when you change a component's key prop during its lifetime—and why it triggers a complete reset.
The Reset Button Effect
When React sees a different key on what looks like the same element in the same position, it doesn't update the existing component. Instead, it unmounts the old one entirely and mounts a brand new instance. This means:
- All component state is destroyed
useEffectcleanup functions run- The DOM node is removed and recreated
- New mounting lifecycle begins from scratch
Think of keys like employee ID badges. If someone shows up to work tomorrow with a different badge number, the system treats them as a completely new person—even if they look the same and sit at the same desk.
Why This Matters
// If itemId changes from "5" to "6":
<UserProfile key={itemId} userId={itemId} />
React will:
- Call cleanup in old component's effects
- Unmount the component (destroying local state)
- Remove the DOM element
- Mount a fresh component instance
- Run all effects from scratch
This is intentional behavior for handling truly different data, but destructive if keys change accidentally (like using random values or unstable identifiers).
Common Mistake
Using Math.random() or array indices that shift causes unintended resets:
// ❌ New key every render = constant remounting
{items.map(item => <Todo key={Math.random()} {...item} />)}
Key Takeaway: Changing a component's key destroys its state and triggers full unmount/remount—use this power intentionally, never accidentally.