Skip to the content

Lesson 162 of 296

Lists and keys

What you will learn

  • Rendering lists with map
  • What keys are and why React needs them
  • Why array indexes make poor keys
  • Choosing good keys
On this page

Rendering a list

Use map (Lesson 60) to turn data into elements:

TSX
type Product = { id: string; name: string; pricePence: number };

function ProductTable({ products }: { products: Product[] }) {
  return (
    <ul>
      {products.map((p) => (
        <li key={p.id}>
          {p.name}: £{(p.pricePence / 100).toFixed(2)}
        </li>
      ))}
    </ul>
  );
}

What is a key?

A key is a special prop that gives each item in a list a stable identity. When the list changes, React uses keys to match each new item with its old version, so it knows which items were added, removed, moved or unchanged.

Without keys (or with bad keys), React matches items by position, which causes bugs and wasted work.

Rules

  • Keys must be unique among siblings (not across the whole app).
  • Keys must be stable: the same item keeps the same key between renders.
  • Put the key on the outermost element returned by map.
  • key is not passed to your component as a prop.

Why the array index is a bad key

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

If you delete the first item, every remaining item's index shifts down by one. React thinks item 0 still exists (it just has different content) and the last item was removed.

Consequences:

  • Any state inside each row (a text input, an "editing" flag, a checked box) stays with the position, so it ends up attached to the wrong item.
  • More DOM updates than needed.

Index keys are acceptable only when the list never reorders, filters, inserts or deletes, and items have no state.

Good keys

SourceExample
Database IDkey={order.id}
A unique fieldkey={user.email}
An ID created when the item is createdcrypto.randomUUID() when adding a new item (Lesson 91)

Never generate keys during render: key={Math.random()} creates a new key every render, so React destroys and recreates every item each time, losing state and focus.

Keys outside lists: resetting a component

Changing a component's key tells React it is a different component, so React throws away the old one (and its state) and creates a fresh one:

TSX
function ChatPanel({ contactId }: { contactId: string }) {
  return <MessageDraft key={contactId} />;
}

function MessageDraft() {
  const [text, setText] = useState("");
  return <textarea value={text} onChange={(e) => setText(e.target.value)} />;
}

When you switch contacts, the draft is reset instead of showing text meant for the previous person. A useful trick that also shows you understand reconciliation (Lesson 163).

How to say it in an interview

"I render lists with map and give each item a key that is unique among siblings and stable across renders, usually a database ID. React uses keys during reconciliation to match items between renders, so it knows what was added, removed or moved. Index keys break when items are inserted, removed or reordered, because state stays with the position, not the item; random keys force every item to remount. Changing a key on purpose is also a clean way to reset a component's state."

Key words

WordMeaning
KeyA stable identity for an item in a list
SiblingsElements with the same parent
RemountDestroying a component and creating it again, losing its state

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.