mediumFrontend EngineerProduct
How does React's reconciliation algorithm work, and why can't you use index as a key in lists?
Posted 18/04/2026
by Mehedy Hasan Ador
Question Details
At a product-based company, the interviewer showed this code:
function TodoList({ items }) {
return (
<ul>
{items.map((item, index) => (
<li key={index}>
<input defaultValue={item.text} />
<button onClick={() => removeItem(index)}>Delete</button>
</li>
))}
</ul>
);
}
> "Users report that after deleting an item, the input values get mixed up. What's wrong and how do you fix it?"Suggested Solution
React's Reconciliation Algorithm
React uses a Virtual DOM diffing algorithm to minimize real DOM operations. When state/props change:1. Creates new Virtual DOM tree
2. Compares (diffs) with previous tree
3. Computes minimum DOM operations needed
4. Applies changes to real DOM
The Key Prop's Role
key tells React which items changed, were added, or removed. It's the identity of each element.Why Index as Key Breaks
Initial state: [Todo A, Todo B, Todo C]
key: 0 key: 1 key: 2
After removing A: [Todo B, Todo C]
key: 0 key: 1
React sees:The Fix
function TodoList({ items }) {
return (
<ul>
{items.map((item) => (
<li key={item.id}>
<input defaultValue={item.text} />
<button onClick={() => removeItem(item.id)}>Delete</button>
</li>
))}
</ul>
);
}
Now React correctly:When Index is OK
Under the Hood
React's diffing uses these rules:1. Different types → teardown old, build new (e.g.,
div → span)2. Same type, different keys → teardown old, build new
3. Same type, same key → update props only