Performance: Keys concept
This concept affects how React updates the UI efficiently by identifying which items changed, added, or removed in lists.
const listItems = items.map(item => <li key={item.id}>{item.name}</li>);const listItems = items.map((item, index) => <li key={index}>{item.name}</li>);| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Index as key | Many unnecessary node replacements | Multiple reflows on reorder | High paint cost due to full updates | [X] Bad |
| Unique stable key | Minimal DOM changes | Single reflow per actual change | Low paint cost with targeted updates | [OK] Good |
map()?item.id ensures each key is unique and stable across renders.index or Math.random() can cause unstable keys leading to rendering bugs. Omitting keys causes React warnings.const items = [
{ id: 1, name: 'Apple' },
{ id: 2, name: 'Banana' },
{ id: 3, name: 'Cherry' }
];
const list = items.map(item => <li key={item.id}>{item.name}</li>);
console.log(list.length);map creates an array of 3 <li> React elements, one for each item.list has 3 elements, so list.length is 3.const items = ['A', 'B', 'C'];
return (
<ul>
{items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
);const users = [
{ id: 1, name: 'Sam' },
{ id: 2, name: 'Alex' },
{ id: 3, name: 'Sam' }
];
return (
<ul>
{users.map(user => <li key={user.name}>{user.name}</li>)}
</ul>
);user.name as key causes duplicates because 'Sam' appears twice.user.id which is unique for each user to avoid React key conflicts.Pass the test and this pattern moves unknown