TechnicalEasy React

Why does React need a key prop when rendering lists?

Asked for Frontend Developer, Full-Stack Developer, Mobile Developer

Why they ask this: Wrong keys cause subtle UI bugs, so this checks practical experience.

Answer

A key gives each list item a stable identity, so React can tell which items were added, removed or reordered between renders and keep the right state and DOM node for each one.

jsx
{todos.map((todo) => (
  <TodoItem key={todo.id} todo={todo} />
))}
  • Use a stable, unique id from your data.
  • Avoid the array index as a key when items can be inserted, deleted or reordered. React would then match state (such as an input's text) to the wrong item.
  • Keys only need to be unique among siblings.

Can you explain this in your own words?

Back to question bank