2dbi
EExpedia Group·Tech KnowledgeL3Design Round

How Do Keys Work in React?

viaLeetCode

Prompt Explain how the key prop works in React and why index-as-key is a bug factory.

Be ready to discuss

  • Reconciliation mechanics: when re-rendering a list, React matches old and new children by key (within the same parent) to decide reuse vs remount; without keys it falls back to positional matching.
  • What a good key is: stable (same item → same key across renders), unique among siblings, derived from identity (id), not position or Math.random() (random keys force full remounts every render).
  • Index-as-key failure modes — walk a concrete one: delete the first item of a list of stateful inputs → every following item shifts index, React reuses each DOM node/component state for the "wrong" logical item → text/focus/checkbox state bleeds to the neighbor. Same for insertions and reorders; also hurts performance (unnecessary re-renders/remounts).
  • When index is acceptable: static, never-reordered, never-filtered lists — and why that's a fragile assumption.
  • Nuances: keys only need uniqueness among siblings; changing a key deliberately is a remount-and-reset-state idiom; key lives on the element in the array (the map callback), not inside the child.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account