React Virtual DOM
Virtual DOM

What is the Virtual DOM?
The Virtual DOM is a lightweight JavaScript representation of the real DOM (Document Object Model).
Instead of directly interacting with the actual browser DOM (which is slow), React creates a copy of the DOM in memory — this is the virtual DOM. React uses this virtual DOM to efficiently determine what changed and update only the necessary parts of the real DOM.
How it works:
-
Initial Render: React renders the entire UI as a virtual DOM tree (in memory). Then, it converts this virtual DOM into the real DOM and displays it in the browser.
-
State or Props Change: A new virtual DOM is created with the updated state or props.
-
Diffing: React compares the new virtual DOM with the previous one using a diffing algorithm. It finds the minimal set of changes required.
-
Patching: React applies those minimal changes (only the differences) to the real DOM, instead of re-rendering the entire page.
Why is this efficient?
- Direct DOM manipulation is slow because it's a heavy operation for the browser.
- React minimizes DOM changes by batching updates and only modifying what's necessary.
- This leads to faster UI updates, better performance, and smoother user experiences.
Example:
Suppose you have a <ul>
with 5 list items, and you update one item:
- In traditional DOM, it may re-render the whole list.
- In React:
- It compares the old and new virtual DOM trees.
- It finds that only one
<li>
changed. - It updates just that one
<li>
in the real DOM.