Sub topic 4
Why Every List Item Needs a Key
This chapter assumes you know JavaScript arrays and map, React function components, props, JSX, and the useState hook. You should also have rendered a basic list with map. Here you will learn what a key is, what React does with it, and which bugs appear when keys are missing or wrong.
The warning you have already seen
When you render a list without keys, React logs a warning like this in the console:
Warning: Each child in a list should have a unique "key" prop.The warning is not cosmetic. A key is the information React uses to decide which item in the new render corresponds to which item in the previous render. Without that information, React has to guess.
What a key is
A key is a special prop you put on the outermost element returned from map. It must be a string or a number. React reads it, uses it internally, and does not pass it to your component. Inside a component, props.key is undefined.
const people = [
{ id: 1, name: 'Ada' },
{ id: 2, name: 'Grace' },
];
function PeopleList() {
return (
<ul>
{people.map(person => (
<li key={person.id}>{person.name}</li>
))}
</ul>
);
}Each <li> gets the key from its data object. The key identifies the item itself, not its position.
What React does with keys
When state changes, React renders your component again and compares the new tree of elements with the previous one. This comparison is called reconciliation. For a list of children, React needs to match old children to new children so it can do three things:
- Keep the existing DOM node and component state for an item that is still present.
- Create new DOM nodes and state for an item that appeared.
- Remove the DOM node and state for an item that disappeared.
With keys, React matches by key. The item with key 2 in the new list is the same item as the one with key 2 in the old list, wherever it now sits. Without keys, React falls back to matching by position, and it warns you because position is usually the wrong identity.
The diagram shows a list where one item is inserted at the top.
Keys a and b are matched to their earlier versions and keep their state. Key c has no match, so React creates it.
What goes wrong without keys
Rendering lists is easy to get right visually and wrong underneath. The bug only shows up when the list changes and the items hold state or DOM state of their own.
Consider a list where each row contains a text input. The input's text lives in the DOM, and React does not track it unless you make the input controlled.
import { useState } from 'react';
function Row({ label }) {
return (
<li>
{label} <input placeholder="Note" />
</li>
);
}
function Notes() {
const [items, setItems] = useState([
{ id: 1, label: 'Milk' },
{ id: 2, label: 'Eggs' },
]);
function addToTop() {
setItems([{ id: Date.now(), label: 'Bread' }, ...items]);
}
return (
<>
<button onClick={addToTop}>Add to top</button>
<ul>
{items.map((item, index) => (
// Wrong: index as key
<Row key={index} label={item.label} />
))}
</ul>
</>
);
}Type a note into the "Milk" row, then click "Add to top". With key={index}, the first row keeps key 0. React sees "key 0 is still here, with a new label" and reuses the existing row, input and all. Your note for Milk now sits next to "Bread", and a fresh empty input appears next to the last row.
Change the key to item.id and the behavior is correct. The Milk row is matched by its id, so it keeps its input text and moves down. React creates only one new row.
Keys must be unique among siblings
Keys only need to be unique among siblings, meaning the items in the same array. Two different lists can use the same keys without conflict. Two items in the same list cannot.
Duplicate keys cause the same kind of mismatch as missing keys. React warns about them, and in updates it may duplicate or omit items. If your data can contain repeated ids, fix the data or build a unique key.
Where the key goes
The key belongs on the element returned directly by the callback in map, not on something nested inside it.
// Correct: key on the outermost element of the callback
{items.map(item => (
<li key={item.id}>
<span>{item.name}</span>
</li>
))}
// Wrong: key on an inner element, so the <li> has no key
{items.map(item => (
<li>
<span key={item.id}>{item.name}</span>
</li>
))}The same rule applies when you extract a component. The key goes on the component call inside map, not on the root element inside the component:
{items.map(item => (
<Row key={item.id} label={item.name} />
))}Keys are not props
Because React consumes the key, a child cannot read it. If a component needs the id, pass it again under another name.
function Row({ id, label }) {
// props.key is undefined here; id is available because we passed it
return <li data-id={id}>{label}</li>;
}
function List({ items }) {
return (
<ul>
{items.map(item => (
<Row key={item.id} id={item.id} label={item.name} />
))}
</ul>
);
}React also warns if you try to read props.key.
Common errors
| Mistake | Symptom | Fix |
|---|---|---|
| No key at all | Console warning, state sticks to the wrong row after inserts or reordering | Add a key from the data |
| `key={Math.random()}` | Every render creates new keys, so every item is destroyed and recreated. Inputs lose focus and state resets. | Use an id that is stored with the data |
| Index as key in a changing list | Wrong state after insert, delete, or sort | Use a stable id |
| Duplicate keys | Warning, and items may be duplicated or dropped on update | Make keys unique within the list |
| Key on an inner element | Warning persists | Move the key to the outermost element returned by `map` |
Generating keys during render is the most common way to make things worse while appearing to fix the warning. A random key silences the message and then forces React to throw away the whole list on every render. Create ids when the data is created, for example when the user adds an item, and store them with the item.
When an index is acceptable
The index is a fallback, and React uses it silently if you give no key. It is acceptable only when all of these are true:
- The list is static: it is never reordered, filtered, inserted into, or removed from.
- The items have no state of their own and no uncontrolled inputs.
- The data has no id and you cannot add one.
Even then, adding an id to the data is usually cheap. The next chapter looks at how to choose good keys in more depth.
Summary of the working model
- A key tells React which item is which between renders.
- React matches by key, preserves state for matches, creates state for new keys, and discards state for missing keys.
- Keys are consumed by React and are not available as props.
- Keys must be unique among siblings, stable across renders, and placed on the outermost element in the
mapcallback.
Exercise
A list of editable rows uses key={index}. A user types into the third row's input, then deletes the first row. What do they see, and what change fixes it?
Show answer
After the deletion, the item that was third is now at index 1, so React reuses the row that holds index 1's DOM and state for it. Index 2 no longer exists, so React removes the last row. The typed text stays in the DOM node at the old position, so it appears next to a different item (or disappears with the removed row). Using a stable id from the data, such as key={item.id}, lets React match each row to its item, so the typed text moves with the correct item.
Exercise
A developer silences the missing-key warning with key={Math.random()}. The list now loses input focus on every keystroke inside a row's controlled input. Why, and how should the key be created?
Show answer
Each render produces new random keys, so React sees no matching keys. It destroys every old row and creates new ones, which drops DOM focus and any local state. The id should be created once when the item is added to the data, for example with crypto.randomUUID() in the add handler, and then stored on the item and used as key={item.id}.