Sub topic 6
Rendering the list with stable keys
This chapter covers how React renders an array of to-dos and why every item needs a key. It assumes you know Array.prototype.map, can write function components with props, and have a working useState array of to-dos from the earlier chapters.
Rendering an array with map
JSX can hold any JavaScript expression, and an array of elements is a valid expression. To show a list, you transform your data array into an array of elements with map:
function TodoList({ todos }) {
return (
<ul>
{todos.map((todo) => (
<li key={todo.id}>{todo.title}</li>
))}
</ul>
);
}React renders each element in the array in order. The key prop is the only extra requirement. If you leave it out, React logs a warning in development: Each child in a list should have a unique "key" prop.
When the list is empty, map returns an empty array and React renders an empty <ul>. Handle that case explicitly if you want a message:
{todos.length === 0 ? <p>Nothing to do yet.</p> : <ul>{/* items */}</ul>}What a key does
Each time state changes, React renders your components again and compares the new element tree with the previous one. This comparison is called reconciliation. For a list, React needs to decide which new element corresponds to which old one. The key is the identity it uses to match them.
- A key that appears in both the old and new list means "same item". React keeps the DOM node and any component state, and only updates props that changed.
- A key that appears only in the new list means a new item. React creates it.
- A key that appears only in the old list means a removed item. React unmounts it and discards its state.
Without keys, React falls back to position. That works only while items never move, which is not true for a to-do list where users delete, reorder, and filter.
Rules for a good key
A key must satisfy three rules:
- It is unique among siblings. Keys only need to be unique within one array, not across the whole app.
- It is stable. The same item has the same key on every render.
- It identifies the item itself, not where it currently sits.
Here are the common choices and how they fare.
| Key source | Unique | Stable | Verdict |
|---|---|---|---|
| `todo.id` assigned at creation | Yes | Yes | Use this |
| Array index | Yes | No, shifts on delete or reorder | Only for static lists |
| `Math.random()` or `crypto.randomUUID()` in render | Yes | No, new on every render | Never |
| `todo.title` | No, users can add duplicates | Changes when edited | Avoid |
The id must be assigned when the to-do is created, in the submit handler, and then stored in state with the item. That is what the add form from the previous chapter does:
setTodos([...todos, { id: crypto.randomUUID(), title, done: false }]);Generating the id inside map is a bug. Every render would produce new keys, so React would unmount and remount every row each time.
If you load to-dos from a server or localStorage, use the stored id. If the data has no id, assign one once when you load it.
Where the key goes
The key belongs on the outermost element returned from the map callback, at the place where you write the array. It does not go inside the component being rendered:
// Correct: key on the element created inside map
{todos.map((todo) => (
<TodoItem key={todo.id} todo={todo} />
))}
// Wrong: key on the <li> inside TodoItem does nothing for the array
function TodoItem({ todo }) {
return <li key={todo.id}>{todo.title}</li>;
}In the second case React still warns, because the elements in the array (<TodoItem />) have no key.
Keys are not passed down as props. Inside TodoItem, props.key is undefined. If the component needs the id, pass it separately, for example todo={todo} and read todo.id.
If each item renders more than one top-level element, use the explicit Fragment form. The short <> syntax cannot take a key:
import { Fragment } from "react";
{todos.map((todo) => (
<Fragment key={todo.id}>
<dt>{todo.title}</dt>
<dd>{todo.done ? "Done" : "Open"}</dd>
</Fragment>
))}Seeing the index-key bug
Index keys often appear to work because the visible text is right. The failure shows up in state that lives inside the row: a text input, a focused element, or a component's own useState. This demo gives each row an uncontrolled note input. Type a note in each row, then click "Remove first".
import { useState } from "react";
function Row({ title }) {
return (
<li>
{title}{" "}
<input aria-label={`Note for ${title}`} />
</li>
);
}
export default function IndexKeyDemo() {
const [items, setItems] = useState([
{ id: 1, title: "Buy milk" },
{ id: 2, title: "Walk dog" },
{ id: 3, title: "Pay rent" },
]);
return (
<div>
<button type="button" onClick={() => setItems(items.slice(1))}>
Remove first
</button>
<ul>
{items.map((item, index) => (
<Row key={index} title={item.title} />
))}
</ul>
</div>
);
}After the click, the data is [Walk dog, Pay rent]. With key={index}, React sees keys 0 and 1 in the new list and matches them to the old rows 0 and 1. It updates their titles but keeps their DOM nodes, so the "Walk dog" row now shows the note you typed for "Buy milk". The last row, key 2, is removed.
Change key={index} to key={item.id} and the behavior is correct. React sees that id 1 is gone, removes that row with its input, and keeps rows 2 and 3 with their notes.
Edge cases
- Duplicate keys. If two siblings share a key, React warns and may duplicate or omit rows on later updates. Duplicates usually come from using titles as keys or from copying an item object without giving the copy a new id.
- Filtering. The filtered view in a later chapter will render only some to-dos. Keys keep working because each key is still unique among the siblings that are rendered. Switching filters mounts rows that appear and unmounts rows that disappear.
- Reordering. If you sort the array, React moves the existing DOM nodes instead of rebuilding them, as long as the keys follow the items.
- Resetting state on purpose. Changing a component's key tells React it is a different component, so it remounts with fresh state. This is a legitimate technique, for example
<EditForm key={todo.id} todo={todo} />so the form restarts when you select another to-do. - Key type. Keys can be strings or numbers. React converts them to strings internally, so
1and"1"collide.
Accessibility note
A key has no effect on the DOM, so it does not appear in the HTML. Screen readers need the list structure, so render real <ul> and <li> elements rather than div elements. The accessibility chapter returns to this.
Exercise
A teammate renders to-dos with todos.map((todo) => <TodoItem key={Math.random()} todo={todo} />). The list looks correct, but a text input inside each TodoItem loses its text and focus every time any to-do is toggled. Explain why, and give the fix.
Show answer
Math.random() produces a new key on every render. React sees every old key as removed and every new key as added, so it unmounts all rows and mounts new ones. Unmounting discards component state and DOM state such as typed text and focus. The fix is to use a stable, unique key that belongs to the item, such as key={todo.id}, with the id created once when the to-do is added.
Exercise
In the IndexKeyDemo component, the user types "2 litres" into the note input of "Buy milk" and then clicks "Remove first" with key={item.id} in place. Which rows are unmounted, and which input shows "2 litres" afterward?
Show answer
Only the row with id 1 ("Buy milk") is unmounted, and its input and the text in it are discarded. The rows for ids 2 and 3 keep their DOM nodes and inputs. No remaining input shows "2 litres".