What is the virtual DOM in React and how does it work?
Quick answer
The virtual DOM is a lightweight JavaScript copy of the UI that React compares with the previous version after each update, so it only changes the parts of the real DOM that actually differ.
When state or props change, React re-runs your component to produce a new tree of React elements (the virtual DOM). It then compares that tree with the previous one in a process called reconciliation, works out the minimal set of changes, and applies only those to the real DOM.
Touching the real DOM is comparatively expensive, and batching updates lets React do it once per update instead of once per change. The virtual DOM is not automatically faster than hand-written DOM code, but it gives you a declarative model: you describe what the UI should look like for the current state, and React figures out how to get there.
Key points
- Virtual DOM = tree of plain objects describing the UI
- Reconciliation compares old and new trees (diffing)
- Only the differences are applied to the real DOM
Questions interviewers ask next
- What is reconciliation?
- What is React Fiber?