Keys in React — React Technical Interview Questions & Answers
Keys in React
Keys in React
- Keys help React match list items across renders. If you delete the first todo, React should not reuse that row’s input state (typed text, focus, checkbox) on the second todo. A stable id from the server — or a uuid you created when the row was born — does that job. Index as key is OK only for a static list that never reorders, inserts in the middle, or deletes.
- Key goes on the outermost element returned from map. Putting key on an inner <span> does nothing useful. If you extract <Row />, the key still belongs on <Row key={t.id} /> in the parent map, not only inside Row’s root div.
- Let’s delete Lab from [Lab, Viva] on the board. With key={id}: Viva keeps whatever you typed. With key={index}: after delete, old index 1 becomes 0, so Viva steals Lab’s input. That demo is the whole keys viva. Draw it once.
- Don’t use Math.random() as key. A new random key every render remounts every row — lost focus, flicker, slow. Don’t use the displayed title if two rows can share a name. Id must be unique among siblings, not globally unique across the whole app (though unique ids are still easier).
- Trap: ‘keys make it faster’ as the only answer. Speed is a side effect. The real reason is identity: which row is which after the array changes. Mention performance second.
- Keys in React — keys t1,t2. Delete Lab → Viva keeps its state. Index 0 would steal Lab’s state.
map items
│ key={id}
▼
React matches rows
│ delete first
▼
later rows keep stateTechnical Interview Tip: Why keys + when index is OK.
Code Examples for Keys in React
Example
// Keys
function Row({ id, title }) {
return <li key={id}>{title}</li>;
}
export default function Todo({ tasks }) {
return (
<ul>
{tasks.map((t) => (
<Row key={t.id} id={t.id} title={t.title} />
))}
</ul>
);
}
Keys in React — keys t1,t2. Delete Lab → Viva keeps its state. Index 0 would steal Lab’s state.
How to Explain Keys in React to an Interviewer
Why not use index as key on a todo list?
Reorder/delete steals state
Is Math.random() a good key?
No