How to render a list in React
Rendering dynamic lists is essential for displaying arrays of data in React applications, from simple todo lists to complex data tables and navigation menus.
As the creator of CoreUI, a widely used open-source UI library, I’ve implemented list rendering in countless React components including data grids, dropdown menus, and dashboard widgets for enterprise applications.
From my expertise, the most efficient approach is to use the JavaScript map()
method with unique key
props.
This method provides optimal performance through React’s reconciliation algorithm and ensures proper component state management during list updates.
Use JavaScript map()
method to render arrays of data with unique key
props for each item.
function UserList({ users }) {
return (
<ul>
{users.map(user => (
<li key={user.id}>
{user.name} - {user.email}
</li>
))}
</ul>
)
}
The map()
method transforms each array element into a React element, creating a list of components from your data. Each rendered element must have a unique key
prop to help React identify which items have changed, been added, or removed. Use stable, unique identifiers like user.id
rather than array indices for keys. This enables React to efficiently update the DOM when the list changes, preserving component state and avoiding unnecessary re-renders.
Best Practice Note:
This is the same approach we use in CoreUI React components for data tables and navigation lists. Avoid using array indices as keys when the list can be reordered - always use unique, stable identifiers from your data for optimal performance and correct behavior.