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

How Stable Keys Enable Reconciliation

React uses keys to match old and new elements, preserving DOM nodes and component state when items move.

How Stable Keys Enable Reconciliation

What you'll learn: How React uses stable keys to efficiently update lists by matching old and new elements, preserving both DOM nodes and component state.


The Core Idea

When you re-render a list, React faces a puzzle: which items from the old list correspond to which items in the new list? Without keys, React has to guess—usually by position. With stable keys, React can confidently match items between renders, even when they've moved, been inserted, or reordered.

This matching process is called reconciliation. When React finds a matching key, it knows "this is the same item, just in a different position," so it reuses the existing DOM node and preserves any component state.

A Library Analogy

Imagine a librarian reshelving books. Without labels (keys), they only know books by their shelf position—if you swap two books, the librarian thinks they're different books and replaces everything. With unique ISBN numbers (stable keys), the librarian recognizes "this is War and Peace, just moved from shelf 3 to shelf 5," and simply slides it over without replacing it.

What Happens During Reconciliation

  1. React builds a map of old elements using their keys
  2. For each new element, React looks up its key in the map
  3. If the key matches, React reuses the existing DOM node and component instance
  4. If the key is new, React creates a fresh element
  5. If an old key is missing, React removes that element

This is why stable keys prevent bugs: when <TodoItem key="todo-42" /> moves from position 0 to position 5, React knows it's the same todo, preserving its checkbox state, text input focus, and internal component state.

Key Takeaway: Stable keys let React match elements across renders, enabling efficient updates that preserve DOM nodes and component state even when list order changes.