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

Key Stability Across Sorts and Filters

Even when list order or visibility changes, stable keys ensure React tracks the correct elements.

Key Stability Across Sorts and Filters

What you'll learn: How stable keys keep React tracking the right elements even when your list changes order or items disappear.

The Core Idea

When you sort a list (alphabetically, by date, etc.) or filter it (show only favorites, search results), the order of items changes and some items may vanish temporarily. React doesn't panic—as long as you use stable keys. Even though the array positions shift, React uses those keys to say "Ah, this is still the same item, just in a different spot."

Think of it like name tags at a party. If people switch seats (sort) or some step outside (filter), you still recognize them by their name tag—not by which chair they're in.

Why This Matters

Without stable keys, sorting feels like you're destroying and recreating everything. With stable keys, React realizes: "Same items, new order—I'll just move them." This preserves:

  • Component state (if your list items have internal state)
  • DOM focus and scroll position
  • Performance (no unnecessary re-rendering)

When you filter a list to show fewer items, then un-filter to show them all again, stable keys let React recognize "Oh, item #42 is back" instead of treating it as brand new.

The Pattern in Practice

Use database IDs or stable client-side IDs as keys. When you sort or filter, React sees the same keys in a different arrangement and handles it intelligently. Avoid index-based keys here—they change meaning when the array changes, breaking the stability guarantee.

Key Takeaway: Stable keys work like permanent ID badges—they let React recognize the same elements across sorts, filters, and re-orders, preserving state and performance.