key gives an element a stable identity among its siblings, so React's reconciler can match items between renders. Elements are matched by type plus key instead of by position, which lets React move, insert and delete the right DOM nodes and keep each item's state attached to the right item. Keys must be unique among siblings and stable across renders. They are usually an id from your data.
When a list re-renders, React compares the old children with the new ones. Without keys it can only compare by index: "the 1st child is still the 1st child". If you insert an item at the top, every item shifts. React then thinks every row changed and re-renders all of them, and any state inside a row (input text, focus, expanded flag) stays with the index, not the data.
function TodoList({ todos }) {
return (
<ul>
{todos.map(todo => (
<TodoRow key={todo.id} todo={todo} />
))}
</ul>
);
}
With key={todo.id}, prepending a todo means React creates one new TodoRow, reuses the existing ones (moving their DOM nodes if needed), and each row keeps its own state.
Math.random() or crypto.randomUUID() during render. It remounts every item on every render, loses state and focus, and is slow.props.key is undefined. Pass id separately if the child needs it.<Fragment key={id}>. The short <> syntax can't take a key.React preserves state while the same component type stays at the same position. Changing the key tells React it's a different instance, so it unmounts the old one and mounts a fresh one:
<ProfileForm key={userId} userId={userId} />
Switching users now resets the form's local state without any useEffect syncing. This is the idiomatic way to "reset state when a prop changes".
<li> instead of the mapped component) do nothing.item.name when names can change remounts the row on rename.key to deliberately reset a component.Spotted a mistake or a rights concern? Report an issue