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.
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.
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.
{items.forEach(i => <li>{i}</li>)} render nothing?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.
Before: the list was Apple (key a), Banana (key b).
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.
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.
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}Picking a good key
| Source of key | Verdict |
|---|---|
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 it | Good for client-made items like new todos. |
| Array index | Only for static lists that never reorder, filter or insert. |
Math.random() or crypto.randomUUID() inside render | Never. A new key every render means React destroys and recreates every row each time, losing all state and focus. |
None picked yet
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 symptom to its cause.
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
idas the key.
Expected:
3 open tasks
• Fix login bug
• Write tests
• Review PRDo not mutate the tasks array.
- 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.