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
map() function directly:
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
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:
However, index keys can negatively impact performance. Elements may get re-ordered unnecessarily.
Ideally, rewrite data to have unique IDs whenever possible.
map()to loop over arrays in JSX
- Provide a
keyprop to uniquely identify elements
keyshould be unique and stable
- By default, use a unique ID as
- Index can work as
keyif 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.