Topic F3
The DOM and virtual DOM diffing
How React compares two trees, and why keys decide how much of the DOM changes.
Watch: one new item is added at the top of a list. Without labels, every item is rewritten; with labels, just one is added.
- moving now
- being checked
- passed / marked
React's two rules
- Different types mean different trees: if a
<div>becomes a<section>, or component A becomes component B, React throws away the whole old branch (state included) and builds a new one. It doesn't try to match what's inside. - Children are matched by key: within a list, React uses
keyto know which element is the same across the old and new renders. Without keys, it matches by position.
Why key={index} causes trouble
An index is a position. Insert a new item at the top and every item gets a new index, so React thinks they all changed. Worse, state tied to the position (half-typed text in an input, a ticked checkbox, focus) stays at the old position and is now attached to the wrong item. Choose "no keys" in the figure: inserting one item touches all four elements.
Code, for programmersStable keys
// bad when the list can be reordered, filtered or prepended
{todos.map((todo, i) => <TodoRow key={i} todo={todo} />)}
// good: an id that belongs to the data and never changes
{todos.map((todo) => <TodoRow key={todo.id} todo={todo} />)}
// also bad: a new key on every render forces a full rebuild each time
{todos.map((todo) => <TodoRow key={Math.random()} todo={todo} />)}An index is only safe if the list is never reordered, filtered or inserted into, and its items hold no state of their own.
Quiz
A list uses key={index}. A new item is inserted at position 0. What happens?
A <Chart> component becomes a <Table> in the same spot. What does React do?
The best key for a list of orders?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.