ReactEasy

What is a key in React?

A key is a special prop you give to elements in a list so React can identify each item across renders. Keys must be unique among siblings and stable over time, which is why IDs from your data are the usual choice.

Rules

  • Put the key on the outermost element returned inside .map(), not on an inner child.
  • Unique among siblings, not globally.
  • Stable: the same item should keep the same key across renders.
  • Keys are not passed to your component as a prop; pass the ID separately if the child needs it.
  • Fragments in a list need <Fragment key={id}> (the short <> syntax cannot take a key).

Good keys

  • Database IDs, UUIDs, slugs.
  • IDs generated once when an item is created (crypto.randomUUID() in the add handler).

Bad keys

  • Math.random() or crypto.randomUUID() during render: every render gets a new key, so every item remounts.
  • Array index when the list can be reordered, filtered or have items inserted. Fine for static lists that never change order.

Keys outside lists

A key on any element tells React "this is a different instance when the key changes". Changing key is the idiomatic way to reset a component's state, for example <ChatRoom key={roomId} />.

Warning

Without keys, React warns "Each child in a list should have a unique key prop" and falls back to index keys.

Code example

tsx
1import { Fragment, useState } from "react";
2
3type Todo = { id: string; text: string };
4
5export function Todos() {
6 const [todos, setTodos] = useState<Todo[]>([
7 { id: "a1", text: "Write tests" },
8 { id: "b2", text: "Ship it" },
9 ]);
10
11 function add(text: string) {
12 // Generate the id once, when the item is created
13 setTodos((t) => [{ id: crypto.randomUUID(), text }, ...t]);
14 }
15
16 return (
17 <>
18 <button onClick={() => add("New task")}>Add</button>
19 <dl>
20 {todos.map((t) => (
21 <Fragment key={t.id}>
22 <dt>{t.text}</dt>
23 <dd>id: {t.id}</dd>
24 </Fragment>
25 ))}
26 </dl>
27 </>
28 );
29}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app