What is the Virtual DOM and how does reconciliation work?
Hint
Lightweight JS copy of the DOM — React diffs old vs new tree, applies minimal patches
Full Answer
The Virtual DOM is a JavaScript object tree that mirrors the real DOM. It's cheap to create and manipulate.
Reconciliation process:
- State/props change triggers a re-render — React calls your component function
- React builds a new Virtual DOM tree
- Diffing — React compares (diffs) new tree with the previous tree
- Committing — React applies only the changed nodes to the real DOM
Diffing heuristics (O(n) instead of O(n³)):
- Elements of different types → tear down and rebuild the whole subtree
- Same type → update only changed attributes
- Lists → use
keyprop to match old and new items
// React sees these as DIFFERENT types → full rebuild
<div>...</div> → <span>...</span> // destroys div, creates span
// Same type → just updates className attribute
<div className="old" /> → <div className="new" />
💡 Reconciliation is why key matters so much in lists. Without a stable key, React might reuse the wrong DOM node, causing subtle bugs like input state being wrong item.
More React Fundamentals Questions
Practice this in a timed sprint
5 free questions, no signup required