Course contentsShow
← React
Lesson 1258 of 2,39632. Lists and Keys Deep DiveFree lesson

The Sorting Problem with Index Keys

How using index breaks when users sort a list, causing React to reuse wrong components and lose state.

The Sorting Problem with Index Keys

What you'll learn: How using array indices as keys causes React to misidentify components when the list order changes, leading to broken state and incorrect UI.

Why Sorting Breaks Index Keys

When you use an item's position in an array as its key (key={index}), you're telling React "this component's identity is tied to its position." This works fine when the list never changes order—but the moment you sort or reorder items, React gets confused.

Imagine you have name tags numbered 1, 2, and 3 in a line. If the people swap positions but keep wearing the same number tags, you'd call the wrong names! React does the exact same thing with index keys.

The Mechanism of Failure

When your list ["Alice", "Bob", "Charlie"] becomes ["Charlie", "Bob", "Alice"] after sorting, React sees:

  • Key 0 was Alice, now it's Charlie → React reuses Alice's component instance for Charlie
  • Key 2 was Charlie, now it's Alice → React reuses Charlie's component instance for Alice

React doesn't destroy and recreate components—it reuses them based on keys. If those components had internal state (like a checkbox, input value, or open/closed toggle), that state stays attached to the position, not the actual data item.

The User-Visible Bug

Users might check a checkbox next to "Alice," click sort, and suddenly "Charlie" appears checked instead. Input values, focus states, and component-level state all stick to the wrong items because React matched them by position, not identity.

Key Takeaway: Index keys break as soon as list order changes because React preserves component state by key, not by content. Sorting with index keys causes React to attach old state to wrong items, creating confusing UI bugs.