Advertisement
Intermediate React, Conditional Rendering & Lists (Keys)

Why is using an array's index as a key generally considered a bad practice?

Short answer

When items are added, removed, or reordered, the index of each item can change even though the actual item stayed the same. This confuses React into thinking the wrong item changed, which can cause visual glitches, lost input values, or unnecessary re rendering.

Save React mock interview
Advertisement
AModel answer
When items are added, removed, or reordered, the index of each item can change even though the actual item stayed the same. This confuses React into thinking the wrong item changed, which can cause visual glitches, lost input values, or unnecessary re rendering. Using a stable and unique id from your actual data avoids this problem completely.
// Risky if the list order can change
todos.map((todo, index) => <li key={index}>{todo.text}</li>);

// Safer, uses a stable unique value from the data itself
todos.map((todo) => <li key={todo.id}>{todo.text}</li>);
Real-world example
A team notices that typing into an input inside a reorderable list sometimes jumps to the wrong row, and fixes the bug by switching from using the array index as the key to using each item's actual unique id.
Likely follow-ups
  • In what situation is it actually safe to use the index as a key?
  • How would you generate a unique id for new items that do not already have one?
Related topics