Performance: Common list rendering mistakes
This affects rendering speed and user interaction responsiveness when displaying lists in React.
const List = ({ items }) => items.map(item => <li key={item.id}>{item.name}</li>);const List = ({ items }) => items.map((item, index) => <li key={index}>{item}</li>);| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Index as key | High (all items re-render) | Many (on any change) | High (full list repaint) | [X] Bad |
| Stable unique keys | Low (only changed items) | Few (minimal) | Low (partial repaint) | [OK] Good |
| Rendering full large list | Very high (thousands of nodes) | Many (heavy layout) | Very high (full repaint) | [X] Bad |
| Virtualized list | Low (only visible nodes) | Few (small layout) | Low (small repaint) | [OK] Good |
| Inline functions in render | Causes extra re-renders | Extra reflows due to re-renders | Increased paint cost | [X] Bad |
| Memoized callbacks | Stable renders | Minimal reflows | Reduced paint cost | [OK] Good |
key prop when rendering lists in React?items array?item.id ensures each key is unique and stable across renders.{items.map(item => <li>{item.name}</li>)}) causes warnings.const items = ['apple', 'banana', 'cherry'];
function FruitList() {
return (
<ul>
{items.map((fruit, index) => (
<li key={index}>{fruit}</li>
))}
</ul>
);
}const users = [{id: 1, name: 'Anna'}, {id: 2, name: 'Ben'}];
function UserList() {
return (
<ul>
{users.map(user => <li key={user.name}>{user.name}</li>)}
</ul>
);
}const tasks = [
{id: 1, title: 'Task A'},
{id: 2, title: 'Task B'},
{id: 1, title: 'Task C'}
];
function TaskList() {
return (
<ul>
{tasks.map((task, index) => (
<li key={/* What to put here? */}>{task.title}</li>
))}
</ul>
);
}Pass the test and this pattern moves unknown