The Bottleneck of DOM Manipulation
Single Page Application frameworks like AngularJS and Backbone.js manage UI updates by mutating the browser DOM directly. However, browser DOM reflows are slow. As layouts grow complex, frequent DOM updates freeze UI threads.
Facebook's open-source framework, React.js, resolves this by introducing the Virtual DOM.
React Principle: The UI is a function of state:
UI = f(state). Never mutate the DOM manually. Let the framework diff layouts.
The Virtual DOM and Reconciliation
Instead of direct DOM manipulations, React maintains a lightweight representation of the layout in memory:
- 1.Virtual DOM Compilation: On state changes, React builds a new Virtual DOM tree.
- 2.Diffing Algorithm: React compares this new tree with the last saved version.
- 3.Reconciliation: React calculates the minimum set of mutations required and applies them to the real DOM, reducing layout reflows.
| Element Update Type | Action | Performance |
|---|---|---|
| Direct DOM Write | Full element redraw. | Slow (recomputes styles). |
| Virtual DOM Diff | Applies targeted updates. | Fast (minimal DOM touch). |
Implementing a Simple Component
// Simple React.js component with JSX in 2014
var ClientGreeting = React.createClass({
render: function() {
return (
<div className="greeting-card">
<h2>Welcome, {this.props.name}!</h2>
<p>Your session is active.</p>
</div>
);
}
});By enforcing a Unidirectional Data Flow (passing props down to child components), React simplifies UI state tracking.