Course contentsShow
← React
Lesson 1246 of 2,39632. Lists and Keys Deep DiveFree lesson

The Consequences of Changing Keys Mid-Lifecycle

When a key changes, React unmounts the old element and mounts a new one, destroying state and triggering full lifecycle.

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
  • useEffect cleanup 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:

  1. Call cleanup in old component's effects
  2. Unmount the component (destroying local state)
  3. Remove the DOM element
  4. Mount a fresh component instance
  5. 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.