CodePark/ questions / Performance: lists & virtualization
START PRACTICINGPRACTICE
Frontend question · React › Performance: lists & virtualization

What happens to the list items each time TodoList re-renders?

function TodoList({ todos }) {
  return (
    <ul>
      {todos.map(todo => (
        <TodoItem key={Math.random()} todo={todo} />
      ))}
    </ul>
  );
}
Every TodoItem is unmounted and remounted, losing its state and DOM

Every TodoItem is unmounted and remounted, losing its state and DOM. Keys must be stable across renders. A random key never matches the previous one. So React treats every item as new. It destroys the old components and DOM nodes, and creates fresh ones.

"Any unique key is fine" is the tempting wrong answer. Unique is not enough: the key must also stay the same between renders. Use a stable ID from the data, such as
todo.id.