Fundamentalsbeginner
Keys and List Rendering
Understand why React requires keys for list items and how incorrect keys cause subtle bugs.
When React renders a list of elements, it needs a stable way to identify which items were added, removed, or reordered between renders. The key prop provides that identity. Without keys — or with unstable keys like array indexes — React can misattribute state and DOM nodes to the wrong items after a list changes.
Keys are like luggage tags at an airport carousel — as long as your bag keeps its tag, baggage handlers (React) can find and route it correctly even if the order of bags on the belt changes; use the belt position as the tag instead and bags get swapped by mistake.
Key Concepts
1
Keys are not passed to the component as a regular prop; React uses them internally purely for reconciliation. A good key is something intrinsic and stable to the data, such as a database ID, not something derived from the item's position in the array.
2
Using the array index as a key seems convenient but breaks down as soon as the list can be reordered, filtered, or have items inserted in the middle — because the index-to-item mapping shifts, React may reuse a DOM node (and its internal state, like an input's focus or a checkbox's checked value) for what is conceptually a completely different item.
3
This is a favorite interview topic because it exposes whether a candidate understands reconciliation at a level deeper than "keys silence a console warning." A strong answer describes concrete bugs: form inputs retaining stale values, animations misfiring, or checked checkboxes appearing on the wrong row after a delete.