What is the Virtual DOM and Why Does React Use It?
The Interview Question
What is the virtual DOM? How does it work and why does React use it?
Expert Answer
The virtual DOM is a lightweight JavaScript representation of the real DOM. It's essentially a tree of plain objects that describes what the UI should look like. When state changes, React creates a new virtual DOM tree, compares it to the previous one using a diffing algorithm, and calculates the minimum set of changes needed to update the real DOM. The reason React uses this approach is that direct DOM manipulation is slow — every time you touch the DOM, the browser may need to recalculate styles, reflow layout, and repaint pixels. By batching all changes and applying them at once, React minimizes these expensive operations. The virtual DOM isn't inherently faster than carefully hand-written DOM updates, but it gives you a declarative programming model while keeping performance good enough for the vast majority of applications.
Key Points to Hit in Your Answer
- Virtual DOM is a JavaScript object tree, not an actual DOM
- React diffs the old and new virtual trees to find minimum changes
- Changes are batched and applied to the real DOM in one pass
- Key insight: it's not that virtual DOM is fast — it's that it lets you write declarative code without terrible performance
- Alternatives exist: Svelte compiles away the virtual DOM entirely; Solid uses fine-grained reactivity
Code Example
// What JSX compiles to — virtual DOM elements
// This JSX:
<div className="card">
<h2>{title}</h2>
</div>
// Becomes this virtual DOM object:
{
type: 'div',
props: {
className: 'card',
children: {
type: 'h2',
props: { children: title }
}
}
}
What Interviewers Are Really Looking For
Entry-level question but interviewers listen for nuance. A great answer doesn't just say 'virtual DOM is faster' — it explains the tradeoff: you get a declarative API and good-enough performance. Mentioning that frameworks like Svelte skip the virtual DOM entirely shows deeper understanding.
Practice This Question with AI Grading
Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.
Start Practicing Free →