Virtual DOM & Reconciliation
Definition
The Virtual DOM (VDOM) is a programming concept where an ideal, or 'virtual', representation of a UI is kept in memory and synced with the 'real' DOM by a library such as ReactDOM. This process is called reconciliation.
Explain Like I'm New
Imagine you have a big messy room (the Real DOM). You want to organize it. Instead of moving heavy furniture around blindly to see if it looks good, you draw a blueprint of the room on a piece of paper (the Virtual DOM) and erase/redraw the furniture there. Once the blueprint is perfect, you compare it to the real room (Diffing), and then move only the exact pieces of furniture that need to change (Reconciliation).
Real World Example
If you have a list of 100 items and you change the text of the 3rd item, React creates a new Virtual DOM tree, compares it to the old Virtual DOM tree, notices only the 3rd item is different, and updates JUST that single <li> element in the browser, instead of wiping out and redrawing all 100 items.
Common Use Cases
- •Providing high performance by minimizing expensive real DOM manipulations
- •Allowing declarative API design (you tell React WHAT the UI should look like, not HOW to update it step-by-step)
Interactive Example
import React, { useState } from 'react'; export default function KeyExample() { const [items, setItems] = useState([{ id: 1, text: 'Apple' }, { id: 2, text: 'Banana' }]); const addItemToTop = () => { // Adding an item to the top of the array setItems([{ id: Date.now(), text: 'New Fruit' }, ...items]); }; return ( <div> <button onClick={addItemToTop}>Add Fruit to Top</button> <ul> {items.map((item, index) => ( // BAD: key={index}. If we add an item to the top, the indexes of Apple and Banana change! // React's diffing algorithm will think Apple became New Fruit, Banana became Apple, etc. // GOOD: key={item.id}. React knows Apple and Banana just moved down, and only inserts 1 new DOM node. <li key={item.id}>{item.text}</li> ))} </ul> </div> ); }
Interview Questions
basic
- What is the Virtual DOM?
- What is the Diffing Algorithm?
intermediate
- Why is manipulating the Real DOM considered slow?
- Why does React require a 'key' prop when rendering lists of elements?
advanced
- What are the two major assumptions React's Diffing algorithm makes for O(n) performance?
- What is React Fiber?
trick
- Is the Virtual DOM a feature exclusive to React?