DevAcademy
LearnReactRendering Lists & Keys
BeginnerReact

Rendering Lists & Keys

Learn how to render arrays of data as JSX elements, and why the key prop matters.

Reading Time

14 min

Lesson

Lesson 5 of 42

Rendering an Array

React can render an array of JSX elements directly. The most common way to build that array is with .map(), transforming each piece of data into a corresponding element.

Rendering a List with .map()

const fruits = ["Apple", "Banana", "Cherry"];

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

Why the key Prop is Required

The key prop helps React identify which items have changed, been added, or been removed between renders. Without stable keys, React may re-render or reorder list items incorrectly, causing subtle bugs — especially with state inside list items.

Rendering Objects with a Unique id

const users = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
];

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

Avoid Using the Array Index as a Key

Using the array index as a key works for static lists that never reorder, but breaks down as soon as items are inserted, removed, or reordered — React can end up matching state to the wrong item. Prefer a stable, unique id from your data instead.

The Problem with Index Keys

// Risky: if the list is reordered or filtered, index-based keys
// can cause React to reuse the wrong DOM node/state for an item.
{items.map((item, index) => (
  <ListItem key={index} item={item} />
))}

Keys Are Not Passed as Props

key is a special attribute used internally by React for reconciliation — it’s never passed down to the component as a regular prop, so if the child needs the same value, pass it again under a different prop name.

Keys Only Need to Be Unique Among Siblings

A key only needs to be unique among the elements in the same list, not globally unique across the entire app.

Best Practice

Use a stable, unique identifier from your actual data (like a database id) as the key whenever possible. Reach for the array index only as a last resort, for lists that are never reordered, filtered, or have items inserted/removed.

Interview Questions

Quick Quiz

1. What is the purpose of the key prop in a list?

2. Why is using the array index as a key risky?

3. Does a key value get passed down to the child component as a regular prop?