Thuta Learning
React
BasicWeb DevelopmentIntermediate

Lists & Keys

ReactLesson 1025 min

What you'll walk away with

  • Turn an array into JSX elements with map(), filtering and sorting first
  • Take keys from stable values such as database ids and put them on the outermost element returned by map
  • Explain the bugs caused by using the index or Math.random() as a key
  • Return more than one element per item with a keyed Fragment

Explain it simply

Explain it simply

At a coat check, every coat gets a numbered ticket. Even if the attendant moves the coats to different hooks, the ticket number makes sure nobody gets the wrong coat back.

In a React list, the key is that ticket. You use map() to turn each array item into an <li> or a component, and give each one a key. When items are added, removed or reordered, React uses the keys to tell which item is which.

Problem → Why → Solution

The problem: the tick jumps to the wrong row

A task list has a checkbox and a Remove button on every row, and the key is the array index. You tick "Buy milk" and then remove that row. The row disappears, but the tick does not: it is now on "Call mom", the next task. A user could easily believe an unfinished task is done.

TaskList.jsx
function TaskList({ tasks, onRemove }) {
  return (
    <ul>
      {tasks.map((task, index) => (
        <li key={index}>
          <input type="checkbox" /> {task.title}
          <button onClick={() => onRemove(task.id)}>Remove</button>
        </li>
      ))}
    </ul>
  );
}
// Tick "Buy milk" (index 0), then remove it:
// "Call mom" moves to index 0 and inherits the tick.

Why does the tick move?

React treats an element with the same key as the same item as before, and reuses its DOM and state. After the removal, key 0 now belongs to "Call mom", but React keeps key 0's checkbox, already ticked, and only updates the text. With key={task.id}, React removes exactly the row that was deleted.

Core concept: map produces elements, keys give them identity

React can render an array of JSX elements, so all you do is turn your data array into an element array with map(): {items.map(item => <li>...</li>)}. To show only some items, filter() before the map; to show them in order, sort a copy such as [...items].sort(), because calling sort() directly on an array from props or state modifies the original data. An arrow function with { } needs an explicit return, while one with ( ) returns automatically.

A key is an item's identity among its siblings. On every re-render, React matches the new keys against the old ones to decide which items were added, removed or moved. A matching key keeps that component's state and DOM; a key that disappeared gets unmounted. If you leave keys out, React warns "Each child in a list should have a unique \"key\" prop." and falls back to the index.

A good key is stable, meaning it does not change between renders, and unique, meaning no two siblings share it. Ids from a database are ideal. If your app creates the data itself, give each item an id with crypto.randomUUID() at the moment you create the item, not while rendering. The index is only safe when the list is never reordered, filtered or edited in the middle.

The key belongs on the outermost element that map() returns: on the component, as in <ProductRow key={p.id} />, not on the <li> inside ProductRow. A key is not a prop, so a component cannot read it as props.key; pass a separate prop such as id={p.id} if it needs the value. Keys only have to be unique within one sibling list, so two different lists may reuse the same ids.

Mental model: tickets for every item
  1. Filter / sort the data (on a copy)
  2. map each item to JSX
  3. Put a stable key on the outer element
  4. React matches old and new by key

A key names the item, not its position in the list.

General pattern

jsx
const visible = items
  .filter((item) => condition(item))
  .sort((a, b) => compare(a, b));   // filter() already returned a copy

return (
  <ul>
    {visible.map((item) => (
      <ItemComponent key={item.id} item={item} />
    ))}
  </ul>
);

Filter and sort before rendering, then map each item to a component. filter() returns a new array, so the sort() after it does not touch the original. Put the key directly on the element that map returns.

Example: a todo list

An array of three todo objects is turned into three <li> elements with map(). Each object already carries an id, which is exactly what the key needs.

jsx
function TodoList() {
  const todos = [
    { id: 1, text: 'Learn React' },
    { id: 2, text: 'Build a project' },
    { id: 3, text: 'Deploy the project' }
  ];

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

Code breakdown

  1. Line 2const todos = [

    Here the data is written inside the component; in a real app it usually comes from props, state or an API response.

  2. Line 3{ id: 1, text: 'Learn React' },

    The id identifies this item for its whole life. Even if the text is edited later, the id stays the same.

  3. Line 10{todos.map(todo => (

    The arrow function with ( ) returns the JSX automatically. With { } you would have to write return yourself.

  4. Line 11<li key={todo.id}>{todo.text}</li>

    The key sits on the <li> that map returns. It does not appear in the HTML; React uses it to update the list.

You should see
A bullet list with three lines will appear — Learn React, Build a project, Deploy the project.

Two elements per item: a keyed Fragment

In a glossary built with <dl>, each item produces two elements, a <dt> and a <dd>. The short <>...</> syntax cannot take a key, so import Fragment from react and write <Fragment key={...}>.

A Fragment adds no extra element to the DOM, so the <dt> and <dd> elements sit directly inside the <dl> and the HTML rules are respected. Wrapping each pair in a <div> instead could break the glossary's styling and the way screen readers announce it.

Glossary.jsx
import { Fragment } from 'react';

export default function Glossary({ terms }) {
  return (
    <dl>
      {terms.map((term) => (
        <Fragment key={term.id}>
          <dt>{term.word}</dt>
          <dd>{term.meaning}</dd>
        </Fragment>
      ))}
    </dl>
  );
}

In real projects

Where this shows up in real projects

Product grids, notification feeds, chat messages, table rows, dropdown options: most of an app's UI is list rendering. Records from an API almost always carry an id, ready to be a key. When a chat app shows a message before the server has confirmed it, it creates a temporary id on the client with crypto.randomUUID() and stores it inside the message object.

Key bugs show up most clearly when rows hold state: an input being edited, an open accordion, an animation, a video player. In drag-and-drop lists and tables with sortable columns, missing stable keys lead to text the user typed landing in the wrong row. With thousands of rows, teams use virtualized list libraries that render only the rows on screen, and keys remain central there too.

Common mistakes

Common mistakes

1. Generating keys during render

Writing key={Math.random()} or key={crypto.randomUUID()} in the JSX creates a new key on every render, so React destroys and rebuilds every item. Inputs lose focus, state is lost, and it is slow. Generate the id once, when the data is created.

2. Forgetting return in a map with braces

todos.map(todo => { <li>{todo.text}</li> }) returns undefined for every item, so nothing appears and no error is shown. Write { return <li>...</li>; } or switch to ( ).

3. Putting the key inside the component

Putting key on the <li> inside ProductRow while the map renders <ProductRow product={p} /> without one still triggers the warning. The key must be on the element the map returns: <ProductRow key={p.id} product={p} />.

Best practices

Best practices

  • Give each list item its own component, such as ProductRow, so the map stays short and the row logic can be tested on its own.
  • Keep filter and sort logic in a pure function like visibleProducts(), outside the JSX, so it can be unit-tested without React.
  • Always design the empty case: a "No results" message helps users far more than an empty <ul>.
  • Never ignore the key warning in the development console; it is often the first sign of a state bug you have not seen yet.

Mini challenge

Mini challenge: products by category

Filter a product array by category, sort it from cheapest to most expensive, and render it with ProductRow components. Show a message when nothing matches.

  • A pure visibleProducts(products, category) returns all products for "all", otherwise only that category, sorted by price
  • The original array must not be modified (sort a copy)
  • In the map, the key is product.id and sits on <ProductRow>
  • When nothing matches, render No products in "category".
ProductList.jsx
const PRODUCTS = [
  { id: 'p1', name: 'Notebook', category: 'stationery', price: 3 },
  { id: 'p2', name: 'Desk lamp', category: 'home', price: 25 },
  { id: 'p3', name: 'Pen set', category: 'stationery', price: 8 },
  { id: 'p4', name: 'Mug', category: 'home', price: 6 },
  { id: 'p5', name: 'Stapler', category: 'stationery', price: 5 },
];

export function visibleProducts(products, category) {
  // TODO: keep all for 'all', otherwise filter by category
  // TODO: return a copy sorted by price, cheapest first
}

function ProductRow({ product }) {
  // TODO: <li>Name - price USD</li>
}

function ProductList({ products, category }) {
  // TODO: empty message, or a <ul> of keyed ProductRow components
}

export default function App() {
  // TODO: render ProductList for 'stationery' and for 'toys'
}

Expected: Stationery list (cheapest first): Notebook - 3 USD, Stapler - 5 USD, Pen set - 8 USD For toys, no list appears; the text No products in "toys". is shown instead.

Show hint

Start with category === 'all' ? products : products.filter(...), and finish with [...matching].sort((a, b) => a.price - b.price). The spread [...] makes a copy, so PRODUCTS keeps its order.

Show solution
ProductList.jsx
const PRODUCTS = [
  { id: 'p1', name: 'Notebook', category: 'stationery', price: 3 },
  { id: 'p2', name: 'Desk lamp', category: 'home', price: 25 },
  { id: 'p3', name: 'Pen set', category: 'stationery', price: 8 },
  { id: 'p4', name: 'Mug', category: 'home', price: 6 },
  { id: 'p5', name: 'Stapler', category: 'stationery', price: 5 },
];

export function visibleProducts(products, category) {
  const matching = category === 'all'
    ? products
    : products.filter((p) => p.category === category);
  return [...matching].sort((a, b) => a.price - b.price);
}

function ProductRow({ product }) {
  return <li>{product.name} - {product.price} USD</li>;
}

function ProductList({ products, category }) {
  const visible = visibleProducts(products, category);
  if (visible.length === 0) {
    return <p>No products in "{category}".</p>;
  }
  return (
    <ul>
      {visible.map((product) => (
        <ProductRow key={product.id} product={product} />
      ))}
    </ul>
  );
}

export default function App() {
  return (
    <>
      <ProductList products={PRODUCTS} category="stationery" />
      <ProductList products={PRODUCTS} category="toys" />
    </>
  );
}

Quick quiz 1 / 3

Which key is best for a list of comments loaded from an API?

Quick quiz 2 / 3

In the problem's index-keyed TaskList, you tick "Buy milk" (the first row) and remove it. Where does the tick end up?

Quick quiz 3 / 3

You render <Row key={user.id} name={user.name} />. Inside function Row({ key, name }), what does logging key print?

What to remember

  • Turn a data array into an array of JSX elements with map(), filtering and sorting a copy before rendering.
  • Keys must be stable and unique among siblings: database ids are ideal, and Math.random() during render never is.
  • Index keys move state to the wrong row when the list is reordered, filtered or edited in the middle.
  • Put the key on the element map returns (use <Fragment key> for groups); components cannot read key as a prop.

React Documentation — React

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Lists & Keys | Thuta Learning