Lists and Keys

Learn how to render lists of data efficiently in React using the `map()` method and the importance of unique keys.


React Lists and Keys Tutorial

Rendering Lists in React

React's power lies in efficiently updating the UI based on changing data. When displaying lists of data, using the map() method is crucial. However, for optimal performance, each list item *must* have a unique key prop.

The map() Method

The map() method iterates over an array and transforms each element into a React element. This is how we create lists of components dynamically.

 const items = ['apple', 'banana', 'orange'];

const listItems = items.map((item) => <li key={item}> {item} </li> );

<ul>{listItems}</ul>

The Importance of Keys

The key prop is essential for React's efficient rendering. It helps React identify which items have changed, been added, or removed. Without unique keys, React may struggle to update the list correctly, leading to performance issues and unexpected behavior (e.g., incorrect component state).

  • Keys should be unique within the list.
  • Keys should be stable and predictable. Ideally, they should correspond to a unique identifier of the item in your data source (e.g., an ID from a database).
  • Avoid using array indexes as keys unless the order of items never changes.

Example: Incorrect Keys

Using array indexes as keys can cause problems if the array is reordered or items are added/removed. React may not correctly update the DOM.

 const items = ['apple', 'banana', 'orange'];

// INCORRECT: Using array index as key
const listItems = items.map((item, index) => <li key={index}> {item} </li> );

<ul>{listItems}</ul>

Example: Correct Keys (using unique IDs)

Using a unique ID from your data source is the best practice.

 const items = [
  { id: 1, name: 'apple' },
  { id: 2, name: 'banana' },
  { id: 3, name: 'orange' },
];

const listItems = items.map((item) => <li key={item.id}> {item.name} </li> );

<ul>{listItems}</ul>