Sub topic 6
Extracting list item components
This chapter assumes you can write function components and pass props. It also assumes you know map and useState, and that you have seen the key prop on list items. You will move the markup for one list item into its own component and see where the key goes afterward. You will also see how extraction affects state that lives inside each item.
Why extract an item component
A map callback that returns one <li> is easy to read. Real list items are rarely that small. They grow to include a checkbox, a title, a badge, a delete button, and sometimes local state. At that point the callback becomes hard to scan, and the list component mixes two jobs: deciding which items to show, and deciding how one item looks.
Extracting an item component separates these jobs:
- The list component owns the array, the filtering, the empty state, and the keys.
- The item component owns the markup for a single row and receives everything it needs as props.
Here is a list with the item markup inline:
function TodoList({ todos, onToggle, onRemove }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
{todo.title}
</label>
{todo.done && <span> (done)</span>}
<button onClick={() => onRemove(todo.id)}>Remove</button>
</li>
))}
</ul>
);
}The same list after extraction:
function TodoItem({ todo, onToggle, onRemove }) {
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
{todo.title}
</label>
{todo.done && <span> (done)</span>}
<button onClick={() => onRemove(todo.id)}>Remove</button>
</li>
);
}
function TodoList({ todos, onToggle, onRemove }) {
return (
<ul>
{todos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={onToggle}
onRemove={onRemove}
/>
))}
</ul>
);
}The <li> moved into TodoItem. The key stayed in TodoList. That second point is the most common source of mistakes, so the next section covers it.
Where the key goes
React uses the key to match each element in the new render to an element in the previous render. It does this by looking at the elements in the array that map returns. In the example above, those elements are the <TodoItem> elements. The <li> is inside TodoItem, so React never sees it as an array member.
The rule is: put the key on the outermost element that the map callback returns.
// Wrong: the key is on the <li> inside the component.
// React warns that each child in a list needs a unique "key" prop,
// because the array elements are <TodoItem>, which have no key.
function TodoItem({ todo }) {
return <li key={todo.id}>{todo.title}</li>;
}
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<TodoItem todo={todo} />
))}
</ul>
);
}// Right: the key is on the element returned from map.
function TodoItem({ todo }) {
return <li>{todo.title}</li>;
}
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
</ul>
);
}A key placed inside the component is not harmful in itself, but it does nothing useful. Your linter and React's console warning point you to the real problem: the array elements have no keys.
The key is not a prop
key is consumed by React. The child component cannot read it.
function TodoItem({ todo, key }) {
console.log(key); // undefined
return <li>{todo.title}</li>;
}If the item needs the id, pass it as a separate prop or read it from the data object. In TodoItem above, todo.id is already available through the todo prop.
Designing the props
Extraction makes you decide what the item receives. Two choices come up often.
Pass the whole object or individual fields. Passing todo={todo} is short and keeps the call site stable when the object gains fields. Passing title and done separately makes the item's needs explicit and is easier to reuse outside a list. Either is fine. Pick one per component and stay consistent.
Pass callbacks that take an id. The item calls onRemove(todo.id). This lets the parent pass the same function to every row, which is simpler than creating a new closure per item in the parent. The item builds the small arrow function itself, where it knows the id.
A table summarizes the split of responsibilities:
| Concern | Lives in the list component | Lives in the item component |
|---|---|---|
| The array and its state | Yes | No |
| Filtering, sorting, empty state | Yes | No |
| `key` | Yes | No |
| Markup for one row | No | Yes |
| State used by only one row | No | Yes |
Local state in items and why keys matter
An item component can hold its own state, such as whether a row is in edit mode. React stores that state per component instance and ties each instance to its key. If the key stays the same across renders, the state is kept. If the key disappears, the instance and its state are discarded.
import { useState } from 'react';
function NoteItem({ note, onRemove }) {
const [expanded, setExpanded] = useState(false);
return (
<li>
<button onClick={() => setExpanded(!expanded)}>
{expanded ? 'Hide' : 'Show'} {note.title}
</button>
{expanded && <p>{note.body}</p>}
<button onClick={() => onRemove(note.id)}>Remove</button>
</li>
);
}
function NoteList({ notes, onRemove }) {
return (
<ul>
{notes.map(note => (
<NoteItem key={note.id} note={note} onRemove={onRemove} />
))}
</ul>
);
}Suppose three notes are listed and the second is expanded. If you remove the first note, theeps its key, so it stays expanded. Now change the key to the array index:
{notes.map((note, index) => (
<NoteItem key={index} note={note} onRemove={onRemove} />
))}After you remove the first note, the old second note moves to index 0. React sees index 0 still exists and reuses the first instance, whose expanded is false. The expanded state now looks like it moved to the wrong note, or disappeared. This bug appears only because the item holds state, which is why it often shows up right after you extract a component. Item components that receive only props and hold no state hide this problem.
Do not define components inside components
When you extract an item, it is tempting to write it right inside the list component to access props through closure:
// Avoid this.
function NoteList({ notes, onRemove }) {
function NoteItem({ note }) {
const [expanded, setExpanded] = useState(false);
// ...
}
return (
<ul>
{notes.map(note => (
<NoteItem key={note.id} note={note} />
))}
</ul>
);
}Every time NoteList renders, it creates a new NoteItem function. React compares component types by identity, so it treats each render's NoteItem as a different component. It unmounts all the old rows and mounts new ones, and all local state resets. This also hurts performance. Define item components at the top level of the module and pass what they need as props.
Items that render more than one element
Sometimes one item needs two sibling elements, such as a <dt> and a <dd>. You have two options.
- Extract a component that returns a Fragment (
<>...</>) and put the key on the component in themap. This works because the key sits on the array element, as before. - Skip the extraction and use
<Fragment key={...}>directly insidemap, because the short fragment syntax cannot take a key.
function GlossaryEntry({ entry }) {
return (
<>
<dt>{entry.term}</dt>
<dd>{entry.definition}</dd>
</>
);
}
function Glossary({ entries }) {
return (
<dl>
{entries.map(entry => (
<GlossaryEntry key={entry.id} entry={entry} />
))}
</dl>
);
}Common errors
- Key inside the component. The warning "Each child in a list should have a unique key" persists. Move the key to the element in
map. - Reading
props.key. It is alwaysundefined. Pass the id under another name if the child needs it. - Spreading props that include a key. Spreading an object that contains a
keyfield onto an element, as in<TodoItem {...todo} />, logs a warning in recent React versions. Passkeyexplicitly and spread the rest. - Components defined in render. State resets on every parent render. Move the definition to module scope.
- Mutating the item's prop. The item must treat
todoas read-only. Changes go through callbacks that update state in the parent.
Checking your understanding
Exercise
A teammate extracts <ProductRow product={product} /> from a products.map(...) call. The <tr> inside ProductRow has key={product.id}, but React still warns about missing keys. Why, and how do you fix it?
Show answer
The elements in the array returned by map are the <ProductRow> elements, and they have no key. A key on the <tr> inside the component is invisible to the array. Remove it from the <tr> and write <ProductRow key={product.id} product={product} /> inside the map callback.
Exercise
A list of NoteItem components uses key={index}. Each item has an expanded state. The user expands the third note and then removes the first note. What do they see, and what is the fix?
Show answer
The notes shift up by one index, but React reuses instances by index. The instance at index 2 (still expanded) now renders what used to be the fourth note, so the expanded state appears on the wrong note, and the expanded third note collapses into whatever instance sat at index 1. The fix is to use a stable id, key={note.id}, so each instance stays with its own note.