Skip to content

QuizNot attempted

Reconciliation and keys

Why is using the array index as key a problem for a list where items can be inserted at the top?
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Keys shift, so React reuses the wrong component instances: state and DOM (e.g. input values) stick to the wrong rows
  • React matches children by key between renders
  • with index keys, inserting at the top shifts every key, so React pairs each existing instance with the wrong item: it re-renders all rows with new props and keeps state and DOM (input values, focus) by position.
  • Use a stable id from the data.
  • Not 'slower to compare': number vs string comparison cost is irrelevant.
  • Not 'throws for numeric keys': numeric keys are allowed.
  • Not 'disables React.memo': memo works, it just sees different props per position.