Lists & Keys
- React
Rendering a collection by mapping an array to elements, and giving each element a stable key so React can track items efficiently across updates.
Prerequisites
- JSX and expressions (see Related Topics)
What you'll understand
- How to render a list from an array
- What a key is and why React needs one
- Why an array index is usually a poor key
Explanation
Rendering a list in React means turning an array of data into an array of elements, and the standard tool is the array map method. You map each item to a piece of JSX, and React renders the resulting collection. Because it is just JavaScript, you can filter, sort, or transform the data first and then map what remains.
Each element in a rendered list needs a key: a special prop holding a value that uniquely and stably identifies that item among its siblings. React uses keys to match elements to data across re-renders, so when the list changes it can tell which items were added, removed, or reordered, and update only those rather than rebuilding everything.
A good key is a stable id that belongs to the data, such as a database id. Using the array index as a key is a common mistake: if the list is reordered, filtered, or has items inserted, the indexes shift, and React can associate the wrong element with the wrong data, causing subtle bugs with state and inputs. Reach for the index only when the list is static and never reorders.
Examples
Map an array to elements, giving each a stable key from the data:
function UserList({ users }: { users: { id: number; name: string }[] }) {
return (
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}Common mistakes
- Omitting the key prop when rendering a list.
- Using the array index as the key for a list that can reorder or change.
- Putting the key on the wrong element instead of the outermost one returned by map.
- Expecting keys to be globally unique; they only need to be unique among siblings.
Best practices
- Render lists with map and return one element per item.
- Give each item a stable, unique key from the data, such as an id.
- Avoid the array index as a key unless the list is static.
- Transform (filter or sort) the data before mapping it to elements.
Further reading
- React, Rendering lists — https://react.dev/learn/rendering-lists