Sub topic 8
Keys and stable identity in lists
This chapter assumes you know JavaScript arrays, basic React components and JSX, and useState. It builds on the previous chapter, where React matched elements by type and position. Keys give React a better way to match items in a list.
Why lists need identity
When a component returns an array of elements, position alone is a poor identity. If you insert an item at the top, every other item moves down one slot. By position, React would see each slot holding a different item and would update or reset all of them.
A key is a special prop that tells React which element is which across renders. React uses it during reconciliation to match each new element with the previous one that had the same key, even if the position changed.
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} />
))}
</ul>
);
}Here todo.id comes from the data. If the list is reordered, filtered, or gets a new item at the front, React still pairs each TodoItem with its earlier instance. Each instance keeps its state and its DOM node, and React only moves nodes where needed.
What a key controls
Matching by key means three things:
- An element with a key seen before is the same instance, so its state is preserved.
- A new key creates a new instance with fresh state.
- A key that disappears unmounts that instance and discards its state.
Keys only need to be unique among siblings, not across the whole app. They are not passed to your component as a prop, so read the value from another prop if the component needs it.
Choosing a good key
Use an ID that comes with the data, such as a database primary key. It must be stable, meaning the same item always has the same key, and unique among its siblings.
| Key source | Safe? | Notes |
|---|---|---|
| `item.id` from the data | Yes | Best choice. |
| ID generated once when the item is created (`crypto.randomUUID()`) | Yes | Store it with the item, not in the render. |
| Array index | Only for static lists | Breaks when items are reordered, inserted, or removed. |
| `Math.random()` in render | No | A new key every render remounts every item. |
React warns if you give no key. If you omit it, React falls back to using the index, which hides the same bugs described below.
The index key bug
Index keys look fine until the list changes. Suppose each row has an uncontrolled input, and you use key={index}. You type in the first row, then delete it. The remaining rows shift up, but their keys (0, 1, ...) now match different data. React reuses the instance for key 0, so the typed text stays in the first row, which now shows a different item.
The visible data is correct because it comes from props. The state that React held inside the instance, such as input text, is attached to the position, not to the item.
Using a key to reset state
A key can also be used outside lists. Changing a component's key tells React it is a different instance, so it discards the old one and mounts a new one.
function Profile({ userId }) {
// Same component type at the same position: state would be kept
// when userId changes. Changing the key forces a fresh instance.
return <EditForm key={userId} userId={userId} />;
}This is the supported way to reset a form when the user it edits changes.
Common errors
- Putting the key on an inner element instead of the outermost element returned from
map. The key belongs on the element directly inside the array. - Using a fragment shorthand
<>in a list. It cannot take a key. Use<Fragment key={id}>instead. - Building keys from mutable fields, such as a name the user can edit. When the field changes, the instance remounts.
Exercise
A list of rows uses key={index}. Each row has a text input holding its own typed value in the DOM. A user types "hello" in row 0 and then deletes the first item of the data array. Where does "hello" appear afterward, and what change fixes it?
Show answer
"hello" stays in row 0, which now displays what used to be the second item. React matched the instance by index, so the input state stayed with the position. Fix it by using a stable key from the data, such as key={item.id}, so the input state follows its item and is removed along with it.
Exercise
A Profile component renders <EditForm userId={userId} /> and keeps unsaved edits in state. When the parent switches to a different user, the old user's edits remain. How do you make React reset the form?
Show answer
Add key={userId} to EditForm. A new key means a new instance, so React unmounts the old form and mounts a fresh one with empty state.