Q5: Why are 'keys' required when rendering lists in React, and why avoid index keys?

Keys give items in a list a stable identity. React uses keys during the reconciliation diffing process to identify which items were added, updated, or removed. Using array indices as keys can lead to subtle rendering bugs, input state corruption, and sub-optimal reconciliation if list items are reordered or filtered.

Unique ID Key Mapping
function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        // RECOMMENDED: Unique item ID key
        <li key={todo.id}>{todo.text}</li>
      ))}
    </ul>
  );
}
💡 Using a unique todo.id ensures React preserves component state correctly when list items move.
Key Takeaways
  • Keys allow React to match Virtual DOM list nodes across re-renders efficiently.
  • Avoid array indices as keys when items can be reordered, inserted, or removed.
Knowledge Check

What issue occurs when using array indices as keys for a dynamic reorderable list?