Performance: Importance of keys
This concept affects how React efficiently updates the UI by minimizing unnecessary DOM changes during re-renders.
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 | More DOM node replacements | Multiple reflows on reorder | Higher paint cost due to layout thrashing | [X] Bad |
| Unique stable key | Minimal DOM updates | Single reflow for changed items | Lower paint cost with stable layout | [OK] Good |
key prop when rendering lists of components?key propkey prop uniquely identifies each element so React can efficiently update or reorder elements without re-rendering the entire list.item.id is stable and unique for each item.Math.random() generates new keys each render (bad). Using undefined index causes errors. Omitting keys causes React warnings.const list = ['a', 'b', 'c'];
return (
<ul>
{list.map((item) => <li key={item}>{item}</li>)}
{list.map((item) => <li key={item}>{item.toUpperCase()}</li>)}
</ul>
);const data = [
{ id: 1, name: 'Alice', posts: [{ id: 101, title: 'Hello' }] },
{ id: 2, name: 'Bob', posts: [{ id: 102, title: 'World' }] }
];
return (
<div>
{data.map(user => (
<section key={user.id}>
<h2>{user.name}</h2>
<ul>
{user.posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
</section>
))}
</div>
);user.id for section keys is stable and unique for users.post.id for li keys is stable and unique for posts within each user.Pass the test and this pattern moves unknown