A to-do app shows a list of tasks, each with a text box for notes. A user types “call the CA” into the notes for the second task, then adds a new task at the top of the list. The note jumps: it now appears beside a different task. No data was corrupted in the database, and the state array in the component is correct. The bug lives in how React matched old list items to new ones, and the fix is a single attribute. To see why, you need a working model of the virtual DOM and reconciliation.
The idea: describe, then compare
The browser’s DOM is the live tree of elements on a page. Changing it is not especially slow per operation, but layout and painting that follow can be expensive, and writing correct code that updates many nodes by hand as data changes is hard.
React takes a different approach. Your components return a description of what the UI should look like for the current data: a tree of plain JavaScript objects called React elements. This lightweight description is what people call the virtual DOM. When state or props change, React calls your components again to get a new description, compares it with the previous one, and applies only the differences to the real DOM. That comparison is called reconciliation.
The benefit is mainly about the programming model: you write “what the screen should be for this data”, not “which nodes to change”. The common claim that the virtual DOM is simply “faster than the real DOM” is misleading. A skilled hand-written update can beat it, and frameworks such as Svelte and Solid achieve excellent performance without a virtual DOM by compiling templates into direct updates. React’s approach is about being fast enough while keeping code declarative.
The rules React uses to compare trees
Finding the minimum set of changes between two arbitrary trees is computationally expensive; general algorithms take roughly cubic time in the number of nodes. React avoids this with heuristics that run in close to linear time and work well for real interfaces:
- Different type, rebuild. If an element changes type, say from a
divto asection, or from one component to another, React destroys the old subtree entirely, including all component state inside it, and builds the new one from scratch. - Same type, update. If the type is the same, React keeps the underlying DOM node or component instance and updates only the attributes or props that changed, then recurses into the children.
- Children are matched by position, unless keyed. When comparing a list of children, React by default pairs the first old child with the first new child, the second with the second, and so on. If children carry keys, React pairs them by key instead.
The first rule has a practical consequence worth remembering: defining a component inside another component’s body creates a new component type on every render, so React tears down and rebuilds that subtree each time, losing focus and state. Define components at module level.
Back to the jumping note
Suppose the list initially has tasks A, B and C, rendered without keys or with the array index as the key. The user types a note into B’s text box. That typed text lives in the DOM input element, or in the state of B’s row component, at position 1.
Now the user adds task N at the top, so the new list is N, A, B, C. Matching by position (or by index, which is the same thing), React pairs old position 0 with new position 0, and so on. It sees that the element at position 0 used to show “A” and now shows “N”, so it updates the label text. Position 1 used to show B and now shows A: update the label. Position 2 changes from C to B. Position 3 is new, so create a row for C.
The labels are all correct, because they come from props. But the input element and any component state at position 1 were reused, not moved. The note typed for B is now sitting next to A. React did the efficient thing given what it knew, which was nothing about identity.
Give each row a key based on the task’s stable ID, and React can see that keys A, B and C still exist and only key N is new. It creates one new row at the top and moves nothing else’s state. The note stays with B. As a bonus, React does less work: one insertion instead of updating every row.
Choosing keys
| Key choice | Verdict | Reason |
|---|---|---|
| Database ID or other stable unique ID | Best | Identity follows the data through inserts, deletes and sorting |
| Array index | Only for static lists | Fine if items never reorder, insert or delete; otherwise state attaches to the wrong item |
| Random value generated during render | Avoid | A new key every render makes React remount every item every time, losing state and focus |
| Content such as a name | Risky | Works until two items share a name or a name is edited |
Keys only need to be unique among siblings in the same list, not across the whole app. And if items genuinely have no ID, for example rows a user is adding before saving, generate an ID once when the item is created and store it with the item, not during rendering.
Using keys on purpose
Because a changed key means “this is a different thing”, you can use a key deliberately to reset a component. A profile editor rendered with the selected user’s ID as its key will start with fresh internal state whenever the selected user changes, instead of carrying the previous user’s half-typed edits across. This is cleaner than writing effects that try to reset each field when a prop changes.
What happens after the diff
Since React 16, reconciliation is performed by an architecture called Fiber, which breaks rendering work into units that can be paused, prioritised and resumed. This allows features such as transitions in React 18, where an urgent update like typing can interrupt a less urgent one like re-rendering a large filtered list. Rendering (calling components and computing the diff) can be interrupted; the commit phase, where changes are written to the real DOM, happens in one go so the user never sees a half-updated screen. None of this changes the rules above, but it explains why component functions should be pure: React may call them more than once before committing.
Written by the RP Strativa Team.
Leave a Reply