Lists and Keys in React
Rendering lists is a very common task in React—users, products, posts, menus, tables, etc. Keys help React identify which items change, are added, or removed.
1. What Are Lists in React?
Lists are created by looping through an array and returning JSX using map().
const numbers = [1, 2, 3, 4];
function NumberList() {
return (
<ul>
{numbers.map(num => (
<li>{num}</li>
))}
</ul>
);
}
2. Using map() Correctly
const users = ["Esa", "Rahim", "Karim"];
{users.map(user => (
<p>{user}</p>
))}
3. What Are Keys?
A key is a unique identifier used by React to track list items.
❌ Without keys → inefficient rendering
✅ With keys → better performance
4. Adding Keys to List Items
const users = [
{ id: 1, name: "Esa" },
{ id: 2, name: "Rahim" },
];
{users.map(user => (
<p key={user.id}>{user.name}</p>
))}
Keys must be:
5. Why Not Use Index as Key?
{users.map((user, index) => (
<p key={index}>{user}</p>
))}
Causes issues when:
Use only if data is static.
6. Rendering Complex Lists
function ProductList({ products }) {
return (
<div>
{products.map(product => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>{product.price}</p>
</div>
))}
</div>
);
}
7. Common Use Cases
8. Best Practices
Lists and keys are essential for:
Every real-world React app uses this pattern extensively.