Looping over arrays to render lists of elements is a common need in React apps. However, there are some special considerations when rendering lists in JSX.
One important aspect is the key
prop. React uses keys to uniquely identify list elements and optimize performance.
Let’s look at how to loop through arrays in JSX, and why keys are important:
Rendering Arrays in JSX
JSX makes looping straightforward - you can use JavaScript’s map()
function directly:
const people = [
{ id: 1, name: 'John'},
{ id: 2, name: 'Mary'},
{ id: 3, name: 'Peter'}
];
function App() {
return (
<ul>
{people.map(person => {
return <Person key={person.id} person={person} />
})}
</ul>
)
}
This loops through the people
array, rendering a <Person>
component for each item.
The Importance of Keys
One important thing to note is the key
prop passed to each <Person>
element:
<Person key={person.id} person={person} />
Keys help React differentiate elements in a list. If keys are missing, React may have trouble identifying list items when the list changes.
Keys should be:
- Unique to each sibling
- Stable across re-renders
Using a unique ID from the data as the key is usually best.
Issues from Missing Keys
Keys prevent issues when rendering list updates, like:
- Duplicate keys - Causes performance issues
- Unstable keys - Causes UI bugs like losing focus
- No keys - Can cause elements to rearrange incorrectly
Not using keys is an anti-pattern in React.
When to Use index as Key
Sometimes data lacks unique IDs. As a last resort, you can use the element index as the key:
{items.map((item, index) => (
<Item key={index} item={item} />
))}
However, index keys can negatively impact performance. Elements may get re-ordered unnecessarily.
Ideally, rewrite data to have unique IDs whenever possible.
Summary
- Use
map()
to loop over arrays in JSX - Provide a
key
prop to uniquely identify elements key
should be unique and stable- By default, use a unique ID as
key
- Index can work as
key
if no IDs, but not ideal
Keys may seem confusing at first, but understanding how React uses them will help you avoid performance issues and bugs in dynamic lists.