React Interview Question: Why Do Lists Need Keys?

A
Author
05 Sep, 2026 1 min read 297 views

Short answer: keys tell React which list item is which between renders. With stable keys, React can move, insert and remove items correctly, keeping each item's DOM node and state attached to the right data.

{todos.map((todo) => (
  <TodoItem key={todo.id} todo={todo} />
))}

Why not the index?

{todos.map((todo, index) => <TodoItem key={index} todo={todo} />)}

Insert an item at the top, and every index shifts. React thinks item 0 is still item 0, so it reuses the first component (and its state, such as a checked box or typed text) for different data. Bugs appear when items have internal state or inputs, and when the list is sorted, filtered or prepended.

Index keys are acceptable only for static lists that never reorder and whose items have no state.

Good keys

  • Stable: the same item always has the same key.
  • Unique among siblings (they don't need to be globally unique).
  • Usually a database ID. Never Math.random(): a new key each render remounts every item.

Bonus: keys to reset state

<ProfileForm key={userId} userId={userId} />

Changing the key tells React it's a different component, so it unmounts the old one and mounts a fresh one with clean state. This is a neat way to reset a form when switching users, without effects.

Was this article helpful?

Comments

No comments yet. Have a question or a tip? Be the first to share it.

Leave a comment

Comments are reviewed before they appear.