Hiprup

Why do we need keys in React lists?

Keys are special string attributes you must add when rendering a list of elements. They give React a stable identity for each item across renders, so the diffing algorithm can match, reorder, and reuse DOM nodes correctly instead of recreating them.

  • Use stable IDs — primary keys from data are best (user.id, todo.id).

  • Avoid array index — if items can be reordered, inserted, or removed, indices cause wrong reuse and subtle bugs (focus loss, wrong inputs).

  • Unique among siblings — keys only need to be unique within their immediate list, not globally.

  • Performance — without good keys React may unmount and remount components, losing state and DOM focus.

  • Not a propkey is consumed by React and not visible to the component itself.

// BAD: Using index as key (buggy with reordering)
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map((todo, index) => (
        <li key={index}>  {/* Don't do this for dynamic lists */}
          <input type="checkbox" />
          {todo.text}
        </li>
      ))}
    </ul>
  );
}

// GOOD: Using unique ID as key
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>  {/* Stable, unique identifier */}
          <input type="checkbox" />
          {todo.text}
        </li>
      ))}
    </ul>
  );
}

With index keys, adding a new todo at the top shifts all indices. React thinks the first item's content changed, the second item's content changed, etc., and re-renders everything.

Checkbox states get mixed up. With unique IDs, React knows exactly which items are new, moved, or removed, and only makes minimal DOM changes.

Explain the concrete bug: index keys + reordering = mixed up checkbox states. Then explain the fix: stable unique IDs.

This shows you understand not just the rule but why it exists.

Why do we need keys in React lists? | Hiprup