What does key do in lists?
Short answer
key is a unique identifier of an item in a list,
which React uses during reconciliation (comparing Virtual DOM trees)
to understand which item stayed, which changed, and which was added or removed.
Why key is needed
When React re-renders a list, it compares the old and new Virtual DOM.
Without key, React does not know
which item corresponds to which - and may re-render everything from scratch.
With key, it knows exactly which item stayed the same, and updates only the changes.
Example without key
const items = ['A', 'B', 'C'];
return (
<ul>
{items.map(item => <li>{item}</li>)}
</ul>
);Now you add a new item at the beginning:
['X', 'A', 'B', 'C']React sees a new Virtual DOM and:
- cannot match old items to new ones;
- thinks that all
<li>elements changed; - re-renders the whole list, even though only one item changed.
This can cause:
- loss of state (for example, input focus);
- flicker during animations;
- extra DOM updates → reduced performance.
Example with key
const items = ['A', 'B', 'C'];
return (
<ul>
{items.map(item => <li key={item}>{item}</li>)}
</ul>
);Now when "X" is added:
- React compares the old and new keys:
["A", "B", "C"]→["X", "A", "B", "C"] - It understands that a new item "X" was added, while the rest stayed the same;
- It updates only one row in the real DOM.
Rules for key
- The key must be unique among siblings
<li key={user.id}>{user.name}</li>- Don't use the array index (
index) as key if the list can change (adding, removing, sorting):
// Bad
items.map((item, i) => <li key={i}>{item}</li>);→ React can mix up items, and you will lose state. 3. A stable identifier fits (for example, an id from the DB):
items.map(item => <li key={item.id}>{item.name}</li>);Example with state inside a list
function Item({ label }) {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>{label}: {count}</button>;
}
function App() {
const [items, setItems] = useState(["A", "B", "C"]);
return (
<>
<button onClick={() => setItems(["X", ...items])}>Add at start</button>
{items.map(item => <Item key={item} label={item} />)}
</>
);
}With key={item}, each <Item> keeps its own state across reorders.
Without key, or with key={index}, all buttons "reset" because React thinks these are new components.
Summary
What key does | Why it's needed |
|---|---|
| Uniquely identifies an item | So React knows which item changed |
| Helps with diffing (reconciliation) | For minimal DOM updates |
| Prevents loss of state | When adding, removing, sorting |
| Not visible in the DOM | Only for React's internal mechanism |
Key rule
Always add a unique, stable
keyfor items in lists. Don't use the array index if the order can change.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.