Keys in Data
Keys are special props you give to items when rendering a list in React, such as <li key={todo.id}>. They tell React which item is which between renders, so it can keep the right DOM nodes and component state attached to the right data when items are added, removed or reordered. Without good keys, lists can show stale input values, lose focus or animate the wrong row.
Why React needs keys
When a list re-renders, React compares the new list of elements with the previous one. If items have keys, React matches old and new elements by key: same key means same item, possibly in a new position. Without keys, React can only match by position, so it assumes the first new item is the old first item, and so on. That works for lists that never change order, but breaks as soon as you insert at the top or sort.
Seeing the difference
import { useState } from 'react';
function TaskRow({ task }) {
// Each row has its own uncontrolled note field
return (
<li>
{task.title} <input placeholder="note" />
</li>
);
}
export default function TaskList() {
const [tasks, setTasks] = useState([
{ id: 'a1', title: 'Write report' },
{ id: 'b2', title: 'Email client' },
]);
function addToTop() {
const id = crypto.randomUUID(); // stable id created once, with the data
setTasks((prev) => [{ id, title: 'New task' }, ...prev]);
}
return (
<>
<button onClick={addToTop}>Add to top</button>
<ul>
{tasks.map((task) => (
<TaskRow key={task.id} task={task} /> // good: id from the data
))}
{/* bad: key={index} would move typed notes onto the wrong task */}
</ul>
</>
);
}
Type a note next to "Write report", then click "Add to top". With key={task.id} the note stays with "Write report". If you switch to key={index}, the note stays at position 0 and now appears next to "New task", because React thinks the item at index 0 is the same one as before.
What makes a good key
- Unique among siblings. Keys only need to be unique within one list, not across the whole app.
- Stable. The same item must get the same key on every render.
- Taken from the data. Database ids, product codes or usernames are ideal.
If your data has no id, create one when the item is created, as addToTop does with crypto.randomUUID(), and store it with the item.
When index keys are acceptable
| List behaviour | Index as key? |
|---|---|
| Static, never reordered or filtered, no inputs or state in rows | Acceptable |
| Items added or removed anywhere except the end | Avoid |
| Sorted or filtered by the user | Avoid |
| Rows contain inputs, toggles or their own state | Avoid |
Key mistakes that cause hard-to-spot bugs
The worst is generating keys during render, such as key={Math.random()} or key={crypto.randomUUID()} inside map. Every render produces new keys, so React believes every item is brand new. It destroys and recreates all rows each time, losing focus and state and wasting work.
Other common slips: putting the key on the wrong element (it belongs on the outermost element returned from map, not on a child inside it), and trying to read props.key inside the child component. React uses the key itself and does not pass it down; if the child needs the id, pass it as a separate prop. Duplicate keys, for example when two items share a name used as the key, trigger a console warning and can make one item disappear.
Keys beyond lists
Changing a component's key forces React to throw it away and mount a fresh one. Writing <ProfileForm key={userId} /> resets the form's state whenever a different user is selected, a clean way to reset a component without extra code.
Rule to remember
Give each list item a unique, stable key from its data, never a random value created during render, and use indexes only for fixed lists without state. Put the key on the element returned by map, and pass ids separately if the child needs them.
Ready to master real-world web development?
Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.