The Document Object Model (DOM) is a tree-like structure that represents everything on a webpage. When JavaScript updates the DOM directly, the browser has to re-render elements, which can become slow for large applications.
React solves this using the Virtual DOM — a lightweight, in-memory copy of the real DOM. React updates the Virtual DOM first and then applies only the necessary changes to the real DOM.
? In short: React = Faster, smarter DOM updates
The DOM (Document Object Model) is a programming interface for HTML and XML documents. It represents the page as a tree, where each node is an element (like <div>, <p>, <button>, etc.).
The Virtual DOM is a virtual copy of the real DOM that lives in memory. When your React state changes:
| Traditional DOM | React Virtual DOM |
|---|---|
| Directly manipulates the real DOM elements. | Uses a virtual copy of the DOM stored in memory. |
| Updates the entire page even for small changes. | Updates only the changed components efficiently. |
| Slower performance in complex applications. | Much faster and more optimized for frequent UI updates. |
| Manual coding needed for state synchronization. | Automatically updates UI based on state changes. |
| Used in plain JavaScript, jQuery, etc. | Used by React for dynamic UI rendering. |
// Traditional DOM example: direct DOM manipulation
<button onclick="changeText()">Click Me</button>
<p id="demo">Old Text</p>
<script>
function changeText() {
document.getElementById("demo").innerHTML = "Text changed!";
}
</script>
// React example: state-driven UI with Virtual DOM
function App() {
const [text, setText] = React.useState("Old Text");
return (
<div>
<button onClick={() => setText("Text changed!")}>Click Me</button>
<p>{text}</p>
</div>
);
}
In the traditional DOM example, when changeText() runs, JavaScript directly finds the element with id="demo" and updates its innerHTML. You are responsible for manually selecting and updating DOM elements.
In the React example, when setText() is called:
"Old Text" to "Text changed!".<p> node) is updated in the real DOM.This makes React faster and safer for complex UIs, because you focus on state and components, while React handles the low-level DOM operations.
useState and useEffect to handle data-driven updates efficiently.