0
0
ReactHow-ToBeginner · 4 min read

How Virtual DOM Works in React: Simple Explanation and Example

In React, the virtual DOM is a lightweight copy of the real DOM that React keeps in memory. When state or props change, React updates the virtual DOM first, compares it with the previous version using a process called diffing, and then updates only the changed parts in the real DOM, making UI updates fast and efficient.
📐

Syntax

The virtual DOM is not a code syntax you write directly but a concept React uses internally. However, you interact with it by writing React components and updating their state or props. React then handles the virtual DOM updates automatically.

Key parts:

  • React.createElement(): Creates virtual DOM elements behind the scenes.
  • ReactDOM.createRoot(): Creates a root to render virtual DOM to real DOM.
  • setState() or useState(): Triggers virtual DOM updates.
javascript
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function Counter() {
  const [count, setCount] = useState(0);
  return (
    React.createElement('div', null,
      React.createElement('p', null, `Count: ${count}`),
      React.createElement('button', { onClick: () => setCount(count + 1) }, 'Increment')
    )
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(React.createElement(Counter));
💻

Example

This example shows a simple counter component. When you click the button, React updates the virtual DOM first, compares it with the old virtual DOM, and then updates only the changed text in the real DOM. This makes the update fast and smooth.

jsx
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Counter />);
Output
Count: 0 [Button labeled 'Increment'] (Clicking the button increases the count number displayed)
⚠️

Common Pitfalls

Some common mistakes when working with React and virtual DOM are:

  • Mutating state directly instead of using setState or useState setter, which prevents React from detecting changes and updating the virtual DOM.
  • Updating the real DOM manually, which can cause React's virtual DOM to get out of sync.
  • Not using keys properly in lists, which can confuse React's diffing algorithm and cause inefficient updates.
jsx
/* Wrong: Mutating state directly */
const [items, setItems] = useState([1, 2, 3]);
// items.push(4); // This mutates state directly - wrong

/* Right: Create new array and update state */
setItems(prevItems => [...prevItems, 4]);
📊

Quick Reference

Remember these points about React's virtual DOM:

  • Virtual DOM is a fast, in-memory copy of the real DOM.
  • React updates virtual DOM first, then applies minimal changes to real DOM.
  • Use setState or useState to trigger updates.
  • Always use keys in lists for efficient diffing.
  • Avoid direct DOM manipulation to keep React in control.

Key Takeaways

React uses a virtual DOM to update the UI efficiently by minimizing real DOM changes.
State or prop changes trigger virtual DOM updates and React compares old and new virtual DOM versions.
React applies only the necessary changes to the real DOM, improving performance.
Avoid mutating state directly and manual DOM changes to keep React's virtual DOM in sync.
Use keys in lists to help React identify elements during virtual DOM diffing.