Skip to content

Keys

The Course
•
15 min study

When a list changes, React has to work out which old item is which new item. Was one removed? Did two swap places? It matches them by key. A key is a string or number that's unique among the siblings and stays the same for the same item, like a database id.

Watch keys at work

Each TaskRow has its own state: whether it's starred. Star Read the lesson, then press Remove first:

JSX
export default function TaskRow({ title }) {
  const [starred, setStarred] = useState(false);

  return (
    <li>
      <button onClick={() => setStarred(!starred)} aria-label={`Star ${title}`}>
        {starred ? "★" : "☆"}
      </button>{" "}
      {title}
    </li>
  );
}
Rows with their own state React · 4 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); import { useState } from "react"; import TaskRow from "./TaskRow.jsx"; const starting = [ { id: 1, title: "Read the lesson" }, { id: 2, title: "Change the lab" }, { id: 3, title: "Do the exercise" }, ]; export default function App() { const [tasks, setTasks] = useState(starting); return ( <main> <h1>Tasks</h1> <p className="muted">Star a task, then remove the first one.</p> <ul> {tasks.map((task, index) => ( <TaskRow key={task.id} title={task.title} /> ))} </ul> <button onClick={() => setTasks(tasks.slice(1))}>Remove first</button>{" "} <button onClick={() => setTasks(starting)}>Start again</button> </main> ); } import { useState } from "react"; export default function TaskRow({ title }) { const [starred, setStarred] = useState(false); return ( <li> <button onClick={() => setStarred(!starred)} aria-label={`Star ${title}`}> {starred ? "★" : "☆"} </button>{" "} {title} </li> ); } body { font: 16px/1.5 system-ui, sans-serif; margin: 0; color: #1c2430; } main { max-width: 32rem; margin: 1.5rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.75rem; } .card { border: 1px solid #d6dde6; border-radius: 8px; padding: 0.75rem 1rem; margin-bottom: 0.75rem; } .card h2 { margin: 0 0 0.25rem; font-size: 1.1rem; } .muted { color: #6b7785; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

The starred task is removed, and the other two keep their own stars, because each row's state follows its key:

JSX
<ul>
  {tasks.map((task, index) => (
    <TaskRow key={task.id} title={task.title} />
  ))}
</ul>

Index keys

Press Start again. Then, in App.jsx, change key={task.id} to key={index}. index is the second argument map passes, the item's position: 0, 1, 2.

Run, star Read the lesson, and press Remove first. Predict what you'll see before you click.

Check your prediction

Change the lab is now starred, although you never starred it. Before the removal, the starred row had key 0. After it, Change the lab is first, so it now has key 0, and React gives it the state that belonged to key 0.

Use the index as a key only for a list that never changes: no reordering, adding or removing. If the rows hold nothing of their own, an index key can look fine even after a removal, which is why it's easy to miss. Once rows keep state, as this star does, they get the wrong item's state. When the data has ids, use them.

No keys at all

Delete the key prop entirely and run. The console shows React's warning: Each child in a list should have a unique "key" prop. Without keys, React falls back to positions, the same problem as index keys, and warns you so you don't do it by accident.

Put key={task.id} back before moving on.

Rules for keys

  • Unique among siblings. Two lists on a page can use the same ids.
  • Stable. Don't generate keys while rendering, as in key={Math.random()}. A new key every render makes React throw away and rebuild every row, losing its state.
  • On the element map returns, here <TaskRow key=...>, not inside TaskRow.
  • A component can't read its own key. If it needs the id, pass it as a separate prop too.
Exercise

Spot the problem

Each of these is in a list that can be reordered. Which key is fine, and what goes wrong with the others?

  1. key={book.isbn}
  2. key={index}
  3. key={Math.random()}
  4. key={book.title} in a list where two books can have the same title
Hint 1: the idea

A key identifies an item, not its current position or the time it rendered. Check identity and uniqueness separately.

Hint 2: a first step

Is it unique among the items? Is it the same for the same item on every render?

Show one solution
  1. Fine. An ISBN identifies the book and doesn't change.
  2. Breaks when the order changes. State follows positions, not items, as you saw in the lab.
  3. Breaks on every render. Every row gets a new key each time, so React rebuilds them all and their state resets.
  4. Breaks with duplicates. Two items with the same key confuse React, and it warns: Encountered two children with the same key.

Was this article helpful?

Your response is saved on this device.