Rendering lists is a fundamental part of building real-world React applications.
In this lesson, you will learn how to display collections of data efficiently using map and how keys help React update the UI correctly.
Rendering Lists with map
In React, lists are rendered using the JavaScript map function.
function FruitList() {
const fruits = ["Apple", "Banana", "Orange"];
return (
<ul>
{fruits.map(fruit => (
<li>{fruit}</li>
))}
</ul>
);
}map transforms each array item into a JSX element.
Why map Instead of for Loops
React expects JSX expressions, not statements.
- for loops are statements
- map returns a new array
This makes map the correct and preferred choice for rendering lists.
What Are Keys?
Keys are special attributes used by React to identify elements in a list.
They help React:
- Track which items changed
- Optimize re-rendering
- Avoid unnecessary DOM updates
Without keys, React cannot efficiently update the UI.
Adding Keys to List Items
Keys must be added to the outermost element inside map.
function FruitList() {
const fruits = ["Apple", "Banana", "Orange"];
return (
<ul>
{fruits.map(fruit => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}Each key must be unique among siblings.
Using IDs as Keys (Best Practice)
The best key is a stable unique ID from your data.
const users = [
{ id: 1, name: "Emre" },
{ id: 2, name: "Ahmet" }
];
function UserList() {
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}IDs ensure predictable rendering behavior.
Why Not Use Index as Key
Using array index as a key can cause bugs.
Problems include:
- Incorrect item updates
- Broken animations
- Unexpected UI behavior
Index keys are acceptable only for static lists that never change.
Rendering Components in Lists
Lists often render components instead of plain elements.
function ProductList({ products }) {
return (
<div>
{products.map(product => (
<ProductCard
key={product.id}
product={product}
/>
))}
</div>
);
}Each component still requires a key.
Conditional Lists
You may want to handle empty lists.
function List({ items }) {
if (items.length === 0) {
return <p>No items found</p>;
}
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
}Always consider the empty state.
Performance Considerations
Good key usage:
- Improves rendering performance
- Prevents unnecessary DOM updates
- Makes React diffs predictable
Keys are not accessible via props — they are used internally by React.
Summary
In this lesson, you learned:
- How to render lists using map
- Why keys are required
- How to choose proper keys
- Why index keys can be dangerous
- Rendering components inside lists
- Handling empty list states
In the next lesson, we will explore styling in React and learn different ways to apply styles to components.