Keys, and Why Index Is Usually Wrong

What a key is. A stable identity for each item, so React can tell which one moved rather than assuming position means identity.

Without keys, React compares by position. Item three is item three. That is fine until the list reorders, filters, or loses an entry near the top.

What goes wrong with an index key. Delete the first row of a list of inputs. Every row shifts up one position, but the keys are still 0, 1, 2. React concludes that nothing moved and only the last row disappeared, so it leaves the DOM nodes where they are. The typed values stay behind on the wrong rows.

The data is correct. The screen is wrong. That combination is very hard to debug, which is why the rule is worth taking seriously before you hit it.

Choosing a key

Index

// risky: position, not identity
items.map((it, i) =>
  <Row key={i} item={it} />
)

Id

// stable: belongs to the data
items.map(it =>
  <Row key={it.id} item={it} />
)
Compare → Index is acceptable only when the list never reorders, never filters, and never has items removed. Never use Math.random(): a new key every render throws the whole list away and rebuilds it.

Keys are for React, not for you. You cannot read a key inside the component. If the child needs the id, pass it as a separate prop as well.

The key only has to be unique among its siblings, not globally.

◈ Graded Component

Render a filterable list. Given the three books below, render one li per book inside a ul, each showing just the title. Add a button with id after1980 that filters the list to books published after 1980, and a button with id all that shows every book again. Give each li a key based on the book id rather than its position.

Checked against what your component renders and how it responds, not against how you wrote it. 3 visible and 2 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back