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 DOMEvery 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.
Read more