Interview frequency: …
Short answer
Keys let React identify unique items between renders and detect items that were added, removed, or moved; using an Index can cause state issues and mix up input values after changes.
Explanation
The Diffing algorithm uses the Key to match child components between render cycles. If the array index is used as a key and an item is inserted at the start or deleted from the middle, the indices of later items change. React may then reuse component state (such as input values and animations) for the wrong data.
Code example
// Proper usage: use a unique, stable ID
function TodoList({ todos }: { todos: { id: string; text: string }[] }) {
return (
<ul>
{todos.map(todo => (
<li key={todo.id}>{todo.text}</li>
))}
</ul>
);
}Common mistakes
- Using Math.random() as a Key, forcing React to destroy and recreate the tree on every render.
Follow-up questions
- What is the Virtual DOM in React, and how does the Reconciliation (Diffing) algorithm work?
- What are Portals in React, and when should you use them?