React Design Philosophy and Virtual DOM
React is a popular JavaScript library for building user interfaces. Developed by Meta, React introduced a new approach to UI rendering that differs from traditional direct DOM manipulation.
1. Declarative vs Imperative Programming
Traditional web development using Vanilla JS is imperative. You write step-by-step instructions telling the browser exactly how to update the page:
// Imperative (Vanilla JS)
const button = document.getElementById("btn");
const container = document.getElementById("content");
button.addEventListener("click", () => {
const newParagraph = document.createElement("p");
newParagraph.textContent = "Data loaded!";
container.appendChild(newParagraph);
});React uses a declarative model. You describe the desired state of the UI, and React handles the updates automatically:
// Declarative (React)
function App() {
const [isLoaded, setIsLoaded] = useState(false);
return (
<div>
<button onClick={() => setIsLoaded(true)}>Load Data</button>
{isLoaded && <p>Data loaded!</p>}
</div>
);
}2. Component-Based Architecture
React structures user interfaces into self-contained, reusable building blocks called Components.
Each component manages:
- Structure: Markup defined in JSX.
- Style: Styled using CSS classes or CSS-in-JS.
- Logic: Internal state and event handlers.
Components can be nested inside other components to construct complex application trees.
3. How the Virtual DOM Works
Directly updating the browser real DOM is slow because it triggers layout recalculation and page repaints. React bypasses this bottleneck using a Virtual DOM.
Here is how the rendering pipeline works:
- Initial Render: React builds a lightweight tree of virtual nodes in memory representing the UI.
- State Update: When component state changes, React creates a new virtual representation reflecting the updated state.
- Diffing Algorithm: React compares the new Virtual DOM tree against the old one to identify exactly what changed.
- Reconciliation: React updates only the specific changed nodes in the real browser DOM, keeping page reflows to a minimum.
4. One-Way Data Flow
In React, data flows in a single direction: down from parent components to child components.
- Props: Immutable configuration parameters passed down from a parent.
- State: Mutable values managed internally by the component itself.
Child components cannot directly modify props passed from a parent. If a child needs to send data back up, the parent must pass down a callback function as a prop.