In React, rendering lists of items efficiently is essential for performance. Keys help React identify which items have changed, are added, or are removed, and they should be unique for each element in the list.
React Lists and Keys
1. Rendering Lists
Rendering a list of items in React is straightforward using the map()
function. Here’s an example:
function NumberList({ numbers }) {
return (
<ul>
{numbers.map((number) => (
<li key={number.toString()}>{number}</li>
))}
</ul>
);
}
In this example, each number is rendered as a list item (<li>
), and the key
attribute is set to the number itself for uniqueness.
2. The Importance of Keys
Keys are essential in React to help identify which items in a list have changed. Without unique keys, React will re-render the entire list instead of only updating the changed elements, impacting performance.
Keys should be:
- Unique among siblings
- Stable (shouldn’t change over time)
3. Using IDs as Keys
If each item in your list has a unique identifier, using that identifier as the key is ideal:
const todoItems = [
{ id: 1, text: "Learn React" },
{ id: 2, text: "Build a Project" },
{ id: 3, text: "Read Documentation" },
];
function TodoList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.text}</li>
))}
</ul>
);
}
In this example, each todoItem
has a unique id
, making it an ideal key for each list item.
4. Avoid Using Indexes as Keys
Using indexes as keys is generally discouraged because they can lead to issues if the list changes (such as items being reordered or removed). It can cause unexpected re-renders and bugs.
5. Rendering Components in Lists
When rendering custom components in a list, remember to pass a unique key to each component. Here’s an example:
function ListItem({ value }) {
return <li>{value}</li>;
}
function NumberList({ numbers }) {
return (
<ul>
{numbers.map((number) => (
<ListItem key={number.toString()} value={number} />
))}
</ul>
);
}
Here, each ListItem
component receives a unique key
prop, allowing React to track changes efficiently.
6. Keys with Dynamic Lists
When working with dynamically updated lists, such as lists that can have items added or removed, it’s crucial to use unique and consistent keys. This ensures that React properly updates only the necessary parts of the list when items change.
7. Summary
In this tutorial, we explored how to render lists in React using the map()
function and why unique keys are crucial for performance and reliable rendering. Always use unique and stable values for keys, avoiding indexes whenever possible.