Why do keys matter when rendering lists in React?
Keys tell React which list item is which between renders, so it can keep the right state with the right item when the list changes order, grows or shrinks.
Explain it simply
Imagine a class photo where students keep changing seats. If you only remember "the person in seat 2", you get confused every time someone moves. If every student wears a name badge, you always know who is who. A key is that name badge for each item in a React list.
When a list re-renders, React compares the new list with the old one. With stable keys it can say "this is still item 42, just in a new position", keep its state and move its DOM element. Without good keys it guesses by position, which can attach one row's typed text or checkbox to another row.
Example
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
// Good: the id stays the same for this todo forever
<li key={todo.id}>
<input type="checkbox" defaultChecked={todo.done} /> {todo.text}
</li>
))}
</ul>
);
}If you used key={index} and deleted the first todo, every item below would shift up one index, and React would reuse the wrong checkbox state for them.
How it works
React's reconciliation matches old and new children by key among siblings. Same key and same component type means "update this one". A new key means "create one". A missing key means "remove that one". Keys only need to be unique among siblings, not across the whole app.
Real-world use
- Lists that can be sorted, filtered or reordered.
- Chat messages, where new items are added at the top.
- Forcing a component to reset: changing its
keymakes React throw away its old state and mount a fresh one, which is handy for "start a new form".
Common mistakes
- Using the array index as the key for lists that change. It is only safe when the list never reorders, inserts or deletes.
- Using
Math.random()as a key. It changes every render, so React recreates every item and loses all state. - Putting the key on the wrong element. It must be on the outermost element returned from
map.
What to say in the interview
"Keys give each list item a stable identity. During reconciliation React matches children by key, so it can keep state and DOM nodes attached to the right item when the list changes. I use a stable id from the data, not the index, whenever the list can be reordered, filtered or edited, because index keys can mix up input state between rows. I also use changing a key on purpose to reset a component."
Follow-up questions
- When is using the index as a key acceptable?
- What happens if two siblings have the same key?
- How can a key be used to reset a component's state?