Rendering lists and keys

Beginner · 6 min

Using .map() to render a list of elements, why React needs a stable key for each item, and the bug the index-as-key shortcut causes.

Before thisComponents and propsThe virtual DOM and reconciliationConditional rendering

Codevolution · 6 min

Rendering lists and keys

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by CodevolutionReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • JSX renders an array of elements directly, so .map() over your data, returning JSX per item, is the standard way to render a list — no special loop syntax is needed.
  • key is a special prop, read by React itself rather than passed to your component, that identifies which array item an element corresponds to across renders.
  • Without a stable key, React's reconciliation can't reliably tell which rendered item is which when the list is reordered, filtered, or has items inserted or removed, and it falls back to matching by position.
  • Using an item's array index as its key looks fine until the list's order changes, at which point items can keep stale state or re-render content attached to the wrong data — because the index, not the item, is what React is tracking.
  • The fix is a key derived from the data itself — a database id, a slug, anything stable and unique to that item across reorders — not from the item's position in the array.

.map() is the whole trick

JSX can render an array of elements just as naturally as it renders one, so turning an array of data into a list of UI is mostly ordinary JavaScript: call .map(), return JSX per item, and embed the result.

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

todos.map(...) here produces an array of <li> elements; { } drops that array directly into the surrounding <ul>. There’s no special “for each” syntax in JSX — .map(), a method you’d use on any array regardless of React, is the standard tool. (If .map() itself, or arrow functions, are unfamiliar, that’s plain JavaScript array and function syntax, covered in the javascript roadmap.)

Run the snippet above as-is and React logs a warning in the console: “Each child in a list should have a unique ‘key’ prop.” The list still renders — but that warning is pointing at a real problem worth understanding, not a formality to silence.

Why React needs a key

Reconciliation, covered a few lessons back, works by comparing the previous render’s tree against the new one to find the minimal set of real DOM changes. For a list, that means answering: “of these five <li> elements before, and these five after, which old one corresponds to which new one?”

Without any other information, React’s only option is to match by position: the first <li> before corresponds to the first <li> after, and so on. That assumption works fine as long as the list never reorders, never has an item inserted in the middle, and never has an item removed from the middle — which is a surprisingly fragile set of conditions for a real app’s data.

key is how you tell React the actual identity of each item, so it doesn’t have to guess from position:

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

key is special: React reads it directly during reconciliation and strips it out before your component ever sees its props — it is not a normal prop you can read inside TodoList or the <li>. With a key in place, React can correctly recognize “the todo with id 7 is still the todo with id 7,” no matter where it now sits in the array, and update, move, or remove exactly the right DOM node.

The index-as-key trap

A common shortcut — reaching for the array index because every item technically needs some key — looks correct at first:

{todos.map((todo, index) => (
  <li key={index}>{todo.text}</li>
))}

This satisfies the console warning and, for a list that’s static or only ever appended to at the end, it genuinely causes no visible problem — the index and the item’s identity happen to stay aligned in that narrow case. The bug shows up the moment the list’s order can change relative to that assumption: a reorder, a filter, or an insertion/removal anywhere but the very end.

Here’s a concrete version of the bug. Say each todo item is expandable, tracking its own open/closed state locally:

function TodoItem({ todo }) {
  const [expanded, setExpanded] = useState(false);
  return (
    <li onClick={() => setExpanded(!expanded)}>
      {todo.text}
      {expanded && <p>{todo.details}</p>}
    </li>
  );
}

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

Suppose the list is [A, B, C], and you expand item B — its TodoItem instance (keyed 1) now has expanded: true. Now a new todo, X, gets inserted at the front, making the list [X, A, B, C]. Positionally, what was at index 1 (B) is now at index 2; what’s now at index 1 is A. But React is matching by key, and the key at index 1 is still just 1 — unchanged as far as React can tell. React therefore assumes the TodoItem instance at key 1 is the same component instance as before, just with new props, and keeps its existing state. The result: A’s row renders already expanded, showing B’s old expanded: true state, which it never asked for — while B itself has silently collapsed. The state didn’t move with the item it belonged to; it stayed attached to a position.

Using todo.id as the key instead fixes this completely: the key for B is still b-2 (or whatever its real id is) no matter where B sits in the array, so React correctly recognizes it as the same item, carries its state with it, and correctly recognizes A and X as needing fresh TodoItem instances of their own.

{todos.map((todo) => (
  <TodoItem key={todo.id} todo={todo} />
))}

The rule to take away: reach for the array index only when a list is provably static — never reordered, filtered, or spliced — and otherwise always derive the key from the data itself.

What the video covers

Codevolution’s episode, from their current React 19 series, explains directly why React needs a key when rendering a list and what goes wrong without one. The .map() mechanics themselves get fuller treatment in the series’ preceding episode, and the index-as-key pitfall specifically gets a dedicated follow-up episode — both linked below — since the primary pick keeps its own runtime tight. This lesson’s worked TodoItem example above is deliberately more concrete about why the index-as-key bug happens than a short video can be in a few minutes; use it alongside whichever of the two companion episodes fills in the piece you want more depth on.

Where this fits

This closes out the React fundamentals group — you can now write components, pass data through props, and render it conditionally and as lists, the core loop every React feature from here on builds on. Next, the roadmap moves to state, events, and forms, starting with handling events in React.

Check yourself

  1. 01How do you render a dynamic list of items in JSX?

    Call .map() on the array, returning a piece of JSX for each item, and embed the resulting array directly inside a {} expression slot. JSX can render an array of elements as naturally as it renders a single one, so no special list-rendering syntax is required beyond that.

  2. 02What is the key prop actually for?

    It's a special prop, read by React during reconciliation rather than passed into your component as an ordinary prop, that gives each item in a rendered list a stable identity. React uses it to match up items between the previous render and the new one, so it can tell which elements were kept, moved, added, or removed, rather than just comparing by position.

  3. 03Concretely, what goes wrong when you use an item's array index as its key and the list is then reordered?

    React matches the old and new trees by key, and the index is the key, not the item's identity. If an item moves from index 2 to index 0, React sees 'the item that was at index 0' as unchanged and assumes whatever item is now at index 0 is the same one as before — attaching any element-local state (like an open/closed toggle, or an input's focus) to the wrong underlying data, since the item that actually moved there was never recognized as having moved.

  4. 04What should you use as a key instead of the array index, and why does it fix the problem?

    A value derived from the item's own data that stays the same across reorders — a database id, a slug, or any other field that's both unique and stable for that specific item regardless of where it sits in the array. Because that key travels with the item rather than with a position, React can correctly recognize the item as the same one even after the list is reordered, filtered, or has items inserted.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark