Course contentsShow
← React
Lesson 172 of 2,3965. Lists and KeysFree lesson

Performance Cost of Unstable Keys

Changing keys force React to destroy and recreate elements, losing state and triggering expensive re-mounts.

Performance Cost of Unstable Keys

What you'll learn: Why changing keys between renders forces React to do expensive work instead of efficient updates.

The Hidden Price of Key Changes

When a key changes for a component that was previously rendered, React doesn't see it as "the same component with updated data." Instead, React interprets this as "the old component is gone, and a completely new component has appeared." This triggers a full unmount-and-remount cycle.

What Happens Behind the Scenes

Here's the expensive sequence React must perform:

  1. Destroy the old component: Run cleanup, discard internal state, remove DOM nodes
  2. Create a brand new component: Initialize fresh state, create new DOM nodes
  3. Insert into the DOM: Browser reflows and repaints

Compare this to what happens with stable keys: React simply updates the existing component's props, keeping state intact and reusing DOM nodes. This is vastly more efficient.

Why This Matters

Unstable keys (like Math.random() or new Date().getTime() on every render) force React to take the slow path every single time. Your components:

  • Lose all internal state
  • Trigger expensive lifecycle methods repeatedly
  • Cause unnecessary browser reflows
  • Create visible jank in animations or transitions
  • Waste CPU cycles recreating identical structures

Think of it like demolishing and rebuilding your house every time you want to repaint a room, instead of just repainting.

The Reconciliation Advantage

Stable keys let React's reconciliation algorithm shine. React can quickly determine "this is the same item, just update it" instead of "delete everything and start over."

Key Takeaway: Unstable keys turn React's efficient update mechanism into an expensive destroy-and-recreate cycle, sacrificing performance and losing component state unnecessarily.