Introduction
Keys help React keep track of items in a list. They make updates faster and avoid bugs.
Keys help React keep track of items in a list. They make updates faster and avoid bugs.
<Component key={uniqueValue} />The key must be unique among siblings.
Use stable values like IDs, not indexes, if the list can change.
const list = ['apple', 'banana', 'cherry']; return ( <ul> {list.map(item => <li key={item}>{item}</li>)} </ul> );
const list = ['apple', 'banana', 'cherry']; return ( <ul> {list.map((item, index) => <li key={index}>{item}</li>)} </ul> );
This component shows a list of fruits. Each fruit has a unique key. When you add a new fruit, React updates only the new item.
import React, { useState } from 'react'; export default function FruitList() { const [fruits, setFruits] = useState(['apple', 'banana', 'cherry']); function addFruit() { setFruits([...fruits, 'orange']); } return ( <div> <button onClick={addFruit} aria-label="Add orange fruit">Add Orange</button> <ul> {fruits.map((fruit, index) => ( <li key={index}>{fruit}</li> ))} </ul> </div> ); }
Never use random values for keys because React needs keys to be stable between renders.
Keys help React identify which items changed, were added, or removed.
Keys must be unique and stable to help React update lists efficiently.
Use keys when rendering lists to avoid bugs and improve performance.
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