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

Reordering Lists: When Index Keys Break

Concrete example showing how index keys cause wrong component state when items are reordered or inserted.

Reordering Lists: When Index Keys Break

What you'll learn: How using array indexes as keys causes React to mix up component state when list items are reordered or inserted.

The Problem with Index Keys

When you use array indexes as keys (like key={index}), React identifies each list item by its position, not its identity. This works fine when your list never changes order. But the moment you reorder, insert, or remove items from the middle of a list, React gets confused about which component is which.

What Actually Happens

Imagine you have a list of input fields where users type their names:

const items = ['Alice', 'Bob', 'Charlie'];

// BAD: Using index as key
{items.map((name, index) => (
  <input key={index} defaultValue={name} />
))}

If a user types in each field, then you insert a new item at position 0, React sees this:

  • Before: key=0 (Alice), key=1 (Bob), key=2 (Charlie)
  • After: key=0 (NEW), key=1 (Alice), key=2 (Bob), key=3 (Charlie)

React thinks the component at key=0 is the same component, just with different props. So it keeps the old state (whatever was typed) but updates the defaultValue. The result? The text users typed stays with the position, not the person.

The Real-World Impact

  • User input gets scrambled
  • Checkbox states move to wrong items
  • Component animations trigger on wrong elements
  • Focus moves unpredictably

Key Takeaway: Index keys break when list order changes because React matches components by position instead of identity—always use stable, unique identifiers for items that can be reordered, inserted, or removed from the middle of a list.