ReactMedium
What is reconciliation?
Reconciliation is React's algorithm for comparing the previous and next element trees after a render and working out the smallest set of changes to apply. It uses two heuristics: elements of different types produce different trees, and key props identify which list items are the same between renders.
The heuristics
- Type comparison at each position:
- Same host type (
divtodiv): keep the DOM node, update changed props. - Same component type: keep the instance and its state, re-render with new props.
- Different type: unmount the old subtree (state and DOM are destroyed) and mount a new one.
- Same host type (
- Keys for children lists: React matches children by
keyinstead of index, so reordering, inserting or deleting items keeps the right state with the right item.
These heuristics make diffing O(n) instead of the O(n³) of a general tree diff.
Fiber
Since React 16 reconciliation runs on the Fiber architecture: work is split into units that can be paused, prioritized and resumed, which enables concurrent features like useTransition and Suspense.
Practical consequences
- Do not define components inside components: a new function each render means a new type, so React remounts it and loses state.
- Use stable, unique keys in lists, not array indexes when items can move.
- Reset state on purpose by changing a component's
key, for example<Profile key={userId} />. - Conditional wrappers (
cond ? <div><Form /></div> : <Form />) change the tree shape and remountForm.
Code example
tsx
1import { useState } from "react";23function Field({ label }: { label: string }) {4 const [value, setValue] = useState(""); // state lives with the component instance5 return (6 <label>7 {label} <input value={value} onChange={(e) => setValue(e.target.value)} />8 </label>9 );10}1112export function Demo({ userId }: { userId: string }) {13 const [asAdmin, setAsAdmin] = useState(false);1415 return (16 <div>17 <button onClick={() => setAsAdmin((a) => !a)}>Toggle</button>18 {/* Same type at same position: state is preserved across toggles */}19 <Field label={asAdmin ? "Admin name" : "Name"} />2021 {/* Different key: React treats it as a new component and resets its state */}22 <Field key={userId} label="Notes for this user" />23 </div>24 );25}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.