Real DOM vs Virtual DOM
Overview
The Real DOM (Document Object Model) is the browser's representation of your webpage. Updating it directly is extremely slow. React solves this by keeping a lightweight copy of the Real DOM in memory, called the Virtual DOM. When state changes, React updates the Virtual DOM first, compares it with the previous version (a process called 'Diffing'), and then calculates the absolute minimum number of changes needed to update the Real DOM (a process called 'Reconciliation').
Syntax
Instead of destroying and recreating the entire <ul>, React diffs the two trees and simply appends the <li>Item 3</li> to the actual Real DOM, making the update blazingly fast.
// Old Virtual DOM Snapshot:
// <ul>
// <li>Item 1</li>
// <li>Item 2</li>
// </ul>
// New Virtual DOM Snapshot:
// <ul>
// <li>Item 1</li>
// <li>Item 2</li>
// <li>Item 3</li> <!-- React detects only this node was added -->
// </ul>Common Pitfalls
- Forgetting to provide unique 'key' props to mapped lists. Without keys, React's diffing algorithm gets confused and may re-render the entire list unnecessarily, ruining performance.
- Assuming the Virtual DOM makes React faster than vanilla JS. It doesn't. Vanilla JS is faster. The Virtual DOM simply makes it easier to write performant code without manual optimization.
Interview Tips
- The terms 'Diffing' and 'Reconciliation' are massive interview buzzwords. Ensure you can explain that the Virtual DOM is just a JavaScript object representing the UI.
Real-World Example
A live stock market dashboard where prices tick every second. React only updates the text of the specific prices that changed, rather than re-rendering the whole massive table.
function StockTicker({ stocks }) {
// Only the rows where stock.price changes will trigger a real DOM update
return (
<table>
<tbody>
{stocks.map(stock => (
<tr key={stock.symbol}>
<td>{stock.symbol}</td>
<td className={stock.isUp ? 'green' : 'red'}>
${stock.price.toFixed(2)}
</td>
</tr>
))}
</tbody>
</table>
);
}