React Basics
React Reconciliation and Diffing
Reconciliation is the algorithm React uses to compare the previous element tree with the new one. It assumes that elements of a different type produce a different tree, and that children in a list can be matched by a stable key — two assumptions that turn a theoretically slow tree-diff into a fast linear pass.
What is Reconciliation and Diffing in React?
Reconciliation is the algorithm React uses to compare the previous element tree with the new one. It assumes that elements of a different type produce a different tree, and that children in a list can be matched by a stable key — two assumptions that turn a theoretically slow tree-diff into a fast linear pass.
Why Reconciliation and Diffing matters
Reconciliation decides whether React updates a DOM node in place or destroys it and builds a new one. When it destroys a node, all its DOM state — text typed in an input, scroll position, focus, component state — is lost. Knowing the rules is how you avoid mysterious "my input keeps clearing" bugs.
Reconciliation and Diffing example
// BAD: the input is a different element type in each branch,
// so React unmounts one and mounts the other — text is lost.
{isEditing ? <input value={text} /> : <p>{text}</p>}
// Same tag, different props: React updates in place and keeps state.
<input value={text} readOnly={!isEditing} />How this works
When the type at a tree position changes from input to p, React cannot reuse the node, so it tears down the subtree and mounts a fresh one. Keeping the same type and toggling a prop instead lets React patch the existing node and preserve everything attached to it.
Key points to remember
- Different element type at the same position → unmount old subtree, mount new one.
- Same type → keep the DOM node, update only changed attributes.
- Lists are matched by key, not by array position.
- Position in the tree matters: the same component rendered in two different branches is two different instances.
Common mistakes with Reconciliation and Diffing
- Using an array index as key in a list that can be reordered, inserted into or filtered.
- Conditionally swapping element types when a prop toggle would do.
- Defining a component inside another component — it becomes a brand-new type on every render, so its whole subtree remounts each time.
You can force React to reset a component deliberately by giving it a changing key — for example key={userId} on a form so it clears when you switch users.
React Reconciliation and Diffing— Interview Questions & FAQs
Why does my form clear itself when the parent re-renders?+
Almost always because the element type or the key at that tree position changed, so React unmounted the old node and mounted a new one. Check for components declared inside other components, and for keys built from array indexes.
