Course outline · 0% complete

0/28 lessons0%

Course overview →

Keys: how React tracks list items

lesson 5-2 · ~12 min · 14/28

Keys: how React tracks list items

When a list re-renders, React must match each new item to an old one to reuse DOM instead of rebuilding it. Position alone is unreliable, items get inserted, removed, and reordered. The key prop gives each item a stable identity:

{tasks.map(task => (
  <TaskItem key={task.id} title={task.title} />
))}

Rules for a good key:

  • Stable: the same item keeps the same key across renders. Database ids are ideal.
  • Unique among siblings: no two items in the same list share a key.
  • Not the array index, whenever the list can reorder, insert, or delete. If item 0 is deleted, every remaining item's index shifts by one, and React matches old state to the wrong items.
key=7 Waterkey=8 Rentkey=9 Momkey=8 Rentkey=9 Mombefore deleteafter deleteStable keys: React matches 8→8 and 9→9, reuses their DOM,and removes key 7. Index keys would mis-match every row.
Deleting the first item. With stable keys React pairs survivors correctly (gold lines) and drops only key 7. With index keys, old row 0 would be matched to the new row 0, the wrong item.

Code exercise · javascript

The index-key bug as a simulation you can run. React keeps per-item component state in a table addressed by key. The list started as ["Water plants", "Pay rent", "Call mom"], the user checked the first row, then deleted it. Watch who inherits the checkmark under index keys versus stable id keys.

Quiz

Spot the bug. Each TaskRow contains a checkbox holding its own checked state: ```jsx {tasks.map((task, i) => ( <TaskRow key={i} task={task} /> ))} ``` The user checks the FIRST row's box, then deletes the first task. What can go wrong?

Problem

You render chat messages that can be deleted, and each message object has a unique id field from the server. What expression should you pass as the key?

Quiz

When is the array index acceptable as a key?