The key attribute
- React course
- Beginner
- Lesson 28/84
- 4 min
Learn why every list item needs a unique key.
The key attribute
React asks you to give each node in a list a key so it can tell which item was added or removed. The key is the item's unique identity.
You write the key directly on the <li>: <li key={item.id}>. React reads the keys to find which li changed and updates only that one.
Keys must be unique among siblings, not across the whole list. The same key is never used twice.
Choosing a stable key
The best key is a field already in the data that is unique: id, email, username. If no such field exists, add an id to the data.
Generating a key from Math.random() is wrong: a new key appears on every render and React redraws everything.
Counters (0,1,2) only work when items are appended and never removed.
Practice ListWithKeys component
Complete the skeleton. Write a ListWithKeys component. The items array has id and name on each item. With .map() turn each item into <li key={item.id}>{item.name}</li>. Export it.
Starter code
// Define ListWithKeys hereSample solution
function ListWithKeys() {
const items = [{ id: 1, name: "Alex" }, { id: 2, name: "Sam" }];
return <ul>{items.map(item => <li key={item.id}>{item.name}</li>)}</ul>;
}
export default ListWithKeys;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The key attribute: fill in the missing part
<li key={____}>{item.name}</li>
<li key={item.id}>{item.name}</li>
Explanation: item.id is stable and unique.
2 When does using the array index as key cause trouble?
React wants stable identity; the index is not stable.- Never
- Only in big lists
- When items are added or removed Correct answer
- Only with text
Explanation: Inserting or removing shifts the index, so React updates the wrong node.
3 The key attribute: match the terms
| Term | Meaning |
|---|---|
id field |
Best key |
Math.random() |
Wrong key |
index |
Append-only lists |
same key twice |
Forbidden |