Keys and DOM State Preservation
You'll learn: How stable keys keep native DOM state (like input values and video playback) from disappearing unexpectedly.
The DOM State Problem
In the last lesson, you learned that keys preserve React component state. But there's another crucial layer: native DOM state. This includes:
- Text typed into an
<input>element - Current playback position in a
<video> - Scroll position in a scrollable container
- Canvas drawing content
- Focus state on form elements
These states live in the actual DOM nodes, not React state. When React unmounts and remounts DOM elements, this native state vanishes.
How Keys Prevent DOM Loss
React uses keys to decide whether to reuse an existing DOM element or destroy and recreate it. With stable keys:
// Stable key — DOM node reused, input value preserved
{items.map(item => (
<input key={item.id} defaultValue={item.name} />
))}
With unstable keys (like index when items reorder):
// Index key — items reorder, DOM nodes get mismatched
{items.map((item, idx) => (
<input key={idx} defaultValue={item.name} />
))}
When items reorder, the first <input> DOM node might now be tied to a different item. Its native value stays the same even though React thinks it's showing different data.
Real-World Example
Imagine a video list where users can reorder videos. Without stable keys, reordering causes the wrong video to keep playing at its current timestamp — the playback state stuck with the DOM element, not the logical video item.
Key Takeaway: Stable keys preserve both component state and native DOM state by keeping React's virtual elements matched to the correct physical DOM nodes across renders.