Performance: Rendering lists in React
This affects how fast the page renders and updates when showing multiple items, impacting user interaction smoothness and load speed.
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 updated) | Many (each update triggers layout) | High (repaints all items) | [X] Bad |
| Unique stable keys | Low (only changed items updated) | Few (minimal layout recalculations) | Low (paints only changed items) | [OK] Good |
| Render all large list | Very high (thousands of nodes) | Many (heavy layout) | Very high (large paint area) | [X] Bad |
| Virtualized list | Low (only visible nodes) | Few (small layout area) | Low (small paint area) | [OK] Good |
map() method when rendering lists in React?map() in Reactmap() method is used to take an array of data and create a new array by transforming each item. In React, this means turning data into React elements.map() does in rendering listsmap() creates a React element for each item, which React can then display on the screen.{items.map(item => <li>{item.name}</li>)} has no key, so React will warn. {items.map(item => <li key={item.id}>{item.name}</li>)} uses a unique id from the item, which is correct. {items.map(item => <li key="index">{item.name}</li>)} uses a string 'index' for all keys, which is not unique. {items.map(item => <li key={Math.random()}>{item.name}</li>)} uses Math.random(), which changes every render and is unstable.{items.map(item => <li key={item.id}>{item.name}</li>)} [OK]const fruits = ['Apple', 'Banana', 'Cherry'];
function FruitList() {
return (
<ul>
{fruits.map((fruit, index) => <li key={index}>{fruit}</li>)}
</ul>
);
}map() creates a list item for each fruit with the fruit name as content.const numbers = [1, 2, 3];
function NumberList() {
return (
<ul>
{numbers.map(number => <li>number</li>)}
</ul>
);
}const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 1, name: 'Carol' }
];
function UserList() {
return (
<ul>
{users.map((user, index) => <li key={`${user.id}-${index}`}>{user.name}</li>)}
</ul>
);
}key={`${user.id}-${index}`} or a unique identifier.Pass the test and this pattern moves unknown