React - Lists & Keys
Lists & Keys
When rendering arrays, provide a stable key
for each item.
Try it: Todo List (Static)
View source
function TodoList(){
const todos = [
{ id: 1, text: 'Learn JSX' },
{ id: 2, text: 'Understand props/state' },
{ id: 3, text: 'Build components' },
];
return (
<ul>
{todos.map(item => <li key={item.id}>{item.text}</li>)}
</ul>
);
}
ReactDOM.createRoot(document.getElementById('try-lists')).render(<TodoList />);
Syntax primer (for newcomers)
array.map(item => ...)
to render lists.key
helps React match elements to data items; use stable IDs (not indexes) when possible.
Common pitfalls
- Using array index as key can cause odd UI behavior during reordering.
- Ensure keys are unique among siblings.
Vocabulary
- Key: Identifier that helps React keep items matched to their DOM nodes.
- Reconciliation: Diffing process React uses to update lists efficiently.
Checks for Understanding
- Why are stable keys important when rendering lists?
- When is it acceptable to use the array index as a key?
Show answers
- They help React match items between renders to avoid incorrect DOM updates.
- When the list is static and never reordered/filtered/inserted (e.g., a fixed menu).
Exercises
- Convert the static array to an editable list with an “Add” button. Ensure newly added items get unique, stable keys.
- Demonstrate a reorder (move item up/down) and verify that item state stays with the right row by using stable keys.
- Render a list of objects fetched from a mock API (array of {id, name}); use
id
as the key.