ReactIntermediate4h

Lists, keys, reconciliation.

How React decides what changed, and why your list key matters.

What is it?

When state changes, React renders a new tree of elements and compares it to the previous one — that's reconciliation. To diff lists efficiently, React needs a stable identifier per item. The key prop is that identifier. Pick it well and React reorders, removes, and inserts items correctly. Pick it poorly and you get bugs that look like state corruption.

Why it matters

key={index} is the most common React anti-pattern. It "works" until you reorder the list — then inputs hold the wrong values, animations play backwards, and components remount when they shouldn't. The fix is free: use a stable id from the data.

What to learn

  • The reconciliation algorithm in plain English
  • Why React identifies elements by position + type by default
  • The key prop: what it tells React
  • Stable keys: unique ids from the data, not array indexes
  • When key={index} is genuinely fine (static, never-reordered lists)
  • The "remount on key change" pattern — <Comp key={user.id} /> to reset state

Common pitfall

Using array index as the key when items can reorder. The pattern bites silently: a controlled input keeps its value tied to its position, not the row it visually represents. Sort, filter, or insert and the wrong data appears in the wrong row. Use item.id if you have one; generate one if you don't.

Resources

Primary (free):

Practice

Build a list of items with controlled inputs (each row has a text field). Add a "Move up" button to each row. First implement with key={index} and watch the input values follow the position, not the item. Then fix with key={item.id}. Done when you can demonstrate both bugs and explain the fix in your own words.

Outcomes

  • Pick a stable key for any list — never array index unless static.
  • Use the "key reset" pattern to remount a component on prop change.
  • Read a reconciliation diff and predict what React will keep vs replace.
  • Diagnose "ghost data" bugs caused by index keys.
Back to Frontend roadmap