Lists and Keys
Use .map() to render arrays of data. Keys help React identify which items changed, added, or removed.
Rendering a List
const fruits = ["Apple", "Banana", "Cherry"];
function FruitList() {
return (
<ul>
{fruits.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}
Every item needs a key prop.
Why Keys Matter
React uses keys to track items during re-renders. Without keys, or with bad keys, React can’t efficiently update the list.
// ❌ Without keys — React warns you
{fruits.map((fruit) => <li>{fruit}</li>)}
// ✅ With stable keys
{fruits.map((fruit) => <li key={fruit}>{fruit}</li>)}
Keys enable React to reuse DOM nodes correctly when items reorder or change.
What Makes a Good Key
Use a stable, unique identifier:
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
];
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
Good keys: database IDs, UUIDs, unique slugs.
Index as Key — Anti-Pattern
Using array index as a key causes bugs when the list reorders:
// ❌ Bad if list can reorder, add, or remove
{items.map((item, index) => (
<li key={index}>{item.name}</li>
))}
Only use index as key if the list is static and never reorders.
Key Rules
- Keys must be unique among siblings, not globally
- Keys must be stable — don’t generate them with
Math.random() - Keys can be strings or numbers
- Don’t use array index if the list can change
Mapping to Components
Pass data as props for cleaner list rendering:
function UserCard({ user }) {
return <div>{user.name}</div>;
}
function UserList({ users }) {
return users.map((user) => (
<UserCard key={user.id} user={user} />
));
}
Best Practices
- Use unique IDs — Database IDs or UUIDs as keys
- Avoid index keys — If list items can reorder or change
- Keep keys stable — Never use
Date.now()orMath.random() - Extract list items to components — Cleaner and more reusable
Common Mistakes
- Using index as key — Causes bugs with reordering
- Using random values — Keys change every render, breaking reconciliation
- Using non-unique keys — Duplicate keys cause rendering issues
- Forgetting keys entirely — React warns and may behave unpredictably