The Performance Cost of Bad Keys
You'll learn how unstable keys force React to throw away and rebuild DOM nodes instead of reusing them, causing unnecessary performance hits.
Why Keys Impact Performance
When React reconciles a list, it uses keys to determine which elements changed, moved, or stayed the same. With stable keys, React can efficiently reuse existing DOM nodes by just moving them around or updating their content.
But when keys change between renders—say, because you're using index as the key in a dynamic list—React thinks the old elements disappeared and new ones arrived. It destroys the old DOM nodes completely and creates brand new ones from scratch.
The DOM Destruction Cost
Creating DOM nodes is expensive. React must:
- Allocate new DOM elements
- Apply all attributes and properties
- Trigger browser layout and paint
- Re-run effects tied to mounting
- Lose focus states, scroll positions, and animations
Analogy: Imagine rearranging hotel guests. With stable room numbers (keys), you just move luggage between rooms. With changing room numbers, you check everyone out, demolish their rooms, build new ones, and check them back in. Same guests, wildly different cost.
Real Impact
In a 1000-item list where items shift order, bad keys can cause:
- 1000 DOM destructions + 1000 DOM creations (instead of just reordering)
- Loss of input focus mid-typing
- Dropped animations
- Janky scrolling
The larger and more dynamic your list, the worse it gets.
Key Takeaway: Unstable keys force React to destroy and recreate DOM nodes unnecessarily, turning cheap reordering operations into expensive mount/unmount cycles—use stable IDs to let React efficiently reuse existing elements.