Skip to content

Lesson 4 of 37Thinking in React

Lists and Keys

Render arrays of data with map, and choose keys that keep each row's state attached to the right item.

13 min read0/4 questions

Almost every screen is a list: messages, products, search results, table rows. Rendering one takes a single map. Choosing the key is where people slip, and the bug it causes (a typed note or a checked box jumping to the wrong row) is a favourite interview question because it shows whether you understand how React updates the page.

From array to elements with map

JSX can render an array of elements: {[<li>a</li>, <li>b</li>]} shows both. So to render data, you transform an array of data into an array of elements with Array.prototype.map.

React
const fruits = ["Apple", "Banana", "Cherry"]; export default function App() { return ( <ul> {fruits.map((fruit) => ( <li key={fruit}>{fruit}</li> ))} </ul> );}

Real data is usually an array of objects, and you can chain filter and sort before map to decide what shows and in what order. Copy before sorting ([...arr].sort() or arr.toSorted()), because sort mutates the original array.

React
type Contact = { id: number; name: string; online: boolean }; const contacts: Contact[] = [ { id: 7, name: "Sam", online: true }, { id: 3, name: "Ada", online: false }, { id: 9, name: "Priya", online: true }, { id: 4, name: "Leo", online: true },]; export default function App() { const visible = contacts .filter((c) => c.online) .toSorted((a, b) => a.name.localeCompare(b.name)); return ( <> <h3>{visible.length} online</h3> <ul> {visible.map((c) => ( <li key={c.id}>{c.name}</li> ))} </ul> </> );}
Quick check
Why does {items.forEach(i => <li>{i}</li>)} render nothing?
Need a nudge? A hint rules out a wrong answer.

What a key is for

Each time a component re-renders, React compares the new list of elements with the previous one (the reconciliation step from the React story lesson). For a list, it has to answer: "which old row is this new row?" The key is the answer. React matches rows by key, not by position.

Matching rows by key after inserting at the top
ulli key=cCherry (new)li key=aAppleli key=bBananaroot

Before: the list was Apple (key a), Banana (key b).

1/3

Keys must be unique among siblings (two lists can reuse the same keys) and stable: the same item must get the same key on every render. A key goes on the outermost element returned from map, and it is not passed to your component as a prop.

The index-key bug, live

If you write key={index}, the key describes the position, not the item. That works until the list is reordered, filtered or added to anywhere but the end. Then React matches by position and attaches the wrong row's state to the wrong item.

This demo uses useState, which you will study properly in the State unit. For now, read const [items, setItems] = useState(start) as "a list this component remembers, plus a function that replaces it and re-renders".

Try this: type a note next to Milk in both lists, then press Add to top.

React
import { useState } from "react"; type Item = { id: number; name: string };let nextId = 3; export default function App() { const [items, setItems] = useState<Item[]>([ { id: 1, name: "Milk" }, { id: 2, name: "Eggs" }, ]); function addToTop() { const id = nextId++; setItems([{ id, name: `Item ${id}` }, ...items]); } return ( <div> <button onClick={addToTop}>Add to top</button> <div style={{ display: "flex", gap: 24 }}> <div> <h4>key=index (broken)</h4> <ul> {items.map((item, index) => ( <li key={index}> {item.name} <input placeholder="note" size={8} /> </li> ))} </ul> </div> <div> <h4>key=item.id (correct)</h4> <ul> {items.map((item) => ( <li key={item.id}> {item.name} <input placeholder="note" size={8} /> </li> ))} </ul> </div> </div> </div> );}

On the left, your note is now next to the new item. React saw keys 0, 1, 2 where there used to be 0, 1, so it reused the first two <li>s (with their typed inputs) for whatever is now in positions 0 and 1, and created a fresh row at the bottom. On the right, key 1 still means Milk, so the note follows Milk.

Predict the outputJavaScript

With index keys, rows are reused by position. The items were A and B, and the user checked the box on row A. Then Z is added to the front. Which item now shows the checked box?

// before: [A (checked)] [B]
items = ["Z", ...items];
// rendered with key={index}
Need a nudge? Hints walk you through it.

Picking a good key

Source of keyVerdict
Database id (user.id, order.uuid)Best. Stable and unique.
A natural unique field (an email, a slug, a filename)Good, if it really is unique and does not change.
crypto.randomUUID() when the item is created and stored with itGood for client-made items like new todos.
Array indexOnly for static lists that never reorder, filter or insert.
Math.random() or crypto.randomUUID() inside renderNever. A new key every render means React destroys and recreates every row each time, losing all state and focus.
Quick checkPick all that apply
Which keys are safe for a todo list where users can add, delete and reorder todos? Pick all that apply.

None picked yet

Need a nudge? A hint rules out a wrong answer.

When map returns more than one element per item, wrap them in a keyed fragment. The short <> syntax cannot take a key, so import Fragment:

import { Fragment } from "react";
 
{terms.map((t) => (
  <Fragment key={t.id}>
    <dt>{t.word}</dt>
    <dd>{t.meaning}</dd>
  </Fragment>
))}
Match the pairs0/4 matched

Match the symptom to its cause.

Choose an item, then its match on the other side.
ChallengeEasy

Open tasks list

Render the open tasks (where done is false) from the tasks array.

  • An <h2> that says how many are open: 3 open tasks.
  • A <ul> with one <li> per open task, containing only the task's title.
  • Sort the open tasks by priority, lowest number first.
  • Use the task's id as the key.

Expected:

3 open tasks
  • Fix login bug
  • Write tests
  • Review PR

Do not mutate the tasks array.

React
const tasks = [ { id: 1, title: "Write tests", done: false, priority: 2 }, { id: 2, title: "Fix login bug", done: false, priority: 1 }, { id: 3, title: "Update README", done: true, priority: 3 }, { id: 4, title: "Review PR", done: false, priority: 3 }, { id: 5, title: "Deploy", done: true, priority: 1 },]; export default function App() { // filter, sort, then map to <li> elements return <div></div>;}
Key terms
key
A string or number that identifies a list item among its siblings, so React can match it between renders.
stable key
One that stays the same for the same item on every render, like a database id.
index key bug
Using the array index as the key makes state follow the position, so it lands on the wrong item after an insert, delete or reorder.
Fragment
<Fragment key={id}> groups several elements per list item when you need a key, since <> cannot take one.