React fundamentals · Scenario
Keys and the index-as-key bug
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
We render this list, then insert a new item at the top. The text in the inputs shifts to the wrong rows and focus jumps. Why, and how do you fix it?
{todos.map((todo, i) => (
<li key={i}><input defaultValue={todo.text} /> {todo.text}</li>
))}
Then
Follow-ups the interviewer asks next
- When is the index acceptable as a key?
- What if the API has no stable id?
- What does
key={Math.random()}do? - How do you use
keyon purpose to reset a component's state (<Profile key={userId} />)?
The answer
What a strong answer covers
- A key is identity among siblings. With an index key, state and DOM stay attached to positions, not to items.
- Use stable ids from the data, or generate an id once when the item is created, not during render.
- The index is fine only for static lists that are never reordered, filtered or prepended.
- Random keys remount every child on every render, which costs performance and loses focus and state.
- Changing a key is the idiomatic way to reset state.
The red pen
Common traps
Avoid:the vague "keys help React tell items apart" with no explanation of state misassignment; thinking keys must be globally unique.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.