How to Use Lists in React

This article provides a quick overview of how lists work in React, explaining how to render multiple components dynamically using JavaScript’s array methods. You will learn how to transition raw data into structured user interface elements, the critical role of the key attribute in list rendering, and best practices for writing clean, performant React list code.

In React, rendering lists of data is a fundamental task used for displaying menus, tables, product feeds, and more. To render a list, you traverse an array of data and convert each item into a React element.

Rendering Lists with the map() Method

The standard way to render lists in React is by using the native JavaScript map() method. The map() method iterates through an array and returns a new array containing JSX elements for each item.

Here is a basic example of how to render an array of strings into an unordered list:

function FruitList() {
  const fruits = ['Apple', 'Banana', 'Orange', 'Mango'];

  return (
    <ul>
      {fruits.map((fruit, index) => (
        <li key={index}>{fruit}</li>
      ))}
    </ul>
  );
}

The Importance of “Keys”

When rendering a list, React requires a unique key prop for each item in the array. Keys help React identify which items have changed, been added, or been removed. This is crucial for React’s virtual DOM reconciliation process, as it allows React to update only the specific elements that changed rather than re-rendering the entire list.

Key Best Practices:

  1. Use Unique Identifiers: The best key is a unique string or number that permanently identifies an item among its siblings, such as a database ID (item.id).
  2. Avoid Using Array Indexes: While using the array index as a key is acceptable as a last resort, it is not recommended if the list can be reordered, filtered, or sorted. Using indexes can lead to rendering bugs and performance issues.
  3. Keep Keys Stable: Keys should not be generated on the fly (e.g., using Math.random()) during rendering, as this forces React to recreate the DOM nodes on every render.

Example with Complex Data

In real-world applications, you will often render lists of objects. Here is an example of rendering a list of user objects using unique IDs as keys:

const users = [
  { id: 'user-1', name: 'Alice' },
  { id: 'user-2', name: 'Bob' },
  { id: 'user-3', name: 'Charlie' }
];

function UserList() {
  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}