Skip to content

Lists and Keys

Rendering arrays of data is one of the most common React tasks. You use map() to transform data into JSX, and key props to help React identify which items changed, were added, or removed.

Rendering Lists with map()

Call .map() on an array inside JSX to produce a list of elements. Each top-level element in the list needs a unique, stable key prop among siblings.

Keys help React match items across renders. Without stable keys, React may reuse the wrong component instance, losing local state and causing bugs in forms and animations.

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <li key={todo.id}>
          <TodoItem todo={todo} />
        </li>
      ))}
    </ul>
  );
}

Use a stable database ID as key — not array index if items can reorder or delete.

Key Rules

// Good — stable unique id
items.map(item => <Row key={item.id} {...item} />)

// OK only for static lists that never reorder
items.map((item, index) => <Row key={index} {...item} />)

// Bad — random key every render
items.map(item => <Row key={Math.random()} {...item} />)
  • Keys must be unique among siblings, not globally unique.
  • Keys should be stable across renders for the same item.
  • Do not generate keys with Math.random() or Date.now() during render.
  • Put key on the outermost element returned from map, not inside the child.

Lists and Keys Reference

Quick guide to list rendering in React.

Topic Guidance
Render list .map(item => <Item key={item.id} />)
Key source Database id, UUID, stable slug
Index as key Only for static, never-reordered lists
Fragment in map <Fragment key={id}> when grouping
Empty list Show placeholder before mapping
Filter + map Filter first, then map with keys

How Keys Affect Remounting

Changing a component's key tells React to destroy the old instance and create a new one. This resets local state — useful for resetting a form when switching records, harmful if accidental.

// Resets CommentForm when postId changes
<CommentForm key={postId} postId={postId} />

Large Lists and Virtualization

Rendering thousands of DOM nodes slows the browser. For long lists, use virtualization libraries like TanStack Virtual or react-window to render only visible rows. See the Virtualization lesson for details.

Common Mistakes

  • Using array index as key when items can be inserted, deleted, or reordered.
  • Forgetting the key prop entirely (React warns in dev).
  • Putting key on a nested element instead of the direct child of the map.
  • Using non-unique keys among siblings.

Key Takeaways

  • Use map() to render lists from array data.
  • Assign stable, unique key props to list items.
  • Avoid index keys for dynamic lists.
  • Changing key forces a component remount.

Pro Tip

If list item state behaves strangely after delete/reorder, check your keys first — index keys are the usual culprit.