DEV Community

Bhupesh Chandra Joshi
Bhupesh Chandra Joshi

Posted on

How React Virtual DOM works under the Hood

What problem the Virtual DOM solves?

Consider this scenario there are two couple in house. The girlfriend is the real dom , when couple has Chit-chat and when girlfriend experiences the intense anger and she rearranges the complete home , Back in the day the old-school/collage days before May 29, 2013(without Virtual DOM). The girl says shift the bed shift + furniture shift + curtains change + lighting change. You need to repaint the whole room. After 5 min she said to you , keep them right.

After the complete demolition of the structure of home, you reset all the home settings. Result you understood the problem - time waste and your girlfriend is still angry.
Enter fullscreen mode Exit fullscreen mode

Virtual DOM, on a path of self-improvement just rearranges the structure , after creating the mini model virtual dom on your mind. You shift the table ,
The rest of the setup is identical, except for the repositioned table. You don't touched your home, it's not joke , it is the real problem virtual dom solves.
So, it blocks the unnecessary DOM manipulations.
In browser unnessary DOM manipulation is slow and costly. The real dom leverages the diffing algorithm similar algorith github utilizes on their commit ,where it represents the paint by +++++=> addition and ------=> deletion of code. Browser updates the content with diffing algorithm, it changes only required , it doesn't touch unnessary jsx elements on web browser.

SO , YOU SHOULD REMEMBER TRIGGER, WHEN girlfriend becomes angry ,don't break whole house, instead of this, create a model and change the necessary.

šŸš€ Real DOM vs Virtual DOM: The Epic Battle Explained with Real-Life Stories! šŸ”„

AKA Difference between Real DOM vs Virtual DOM

Hey friend! Grab your favorite drink, sit comfortably, and let's dive in! šŸ’Ŗ

Imagine You're Running a Super Busy Restaurant šŸ½ļø

Real DOM = Your Physical Restaurant (Slow & Expensive)

  • Every single order (change) forces you to shut down the entire restaurant, rearrange tables, repaint walls, move furniture, and rebuild the kitchen — even if only one table ordered extra fries!
  • Tiny update? Whole place gets disrupted → customers (users) get angry, everything slows down, lights flicker, music stops.
  • This is exactly how the Real DOM works in the browser.
    • It's the actual living HTML page.
    • Change one thing (like updating a like counter) → browser recalculates everything (layout, styles, positions).
    • Result? Slow performance, laggy apps, high battery drain. 😩

Virtual DOM = Your Smart Digital Ordering App (Fast & Genius) ⚔

  • You have a digital twin of your restaurant on a super-fast tablet.
  • Customer wants extra fries? You quickly edit it on the tablet (Virtual DOM).
  • The app compares (Diffing) the new order with the old one and says: "Only Table 7 needs fries — just tell the chef that!"
  • Only that one small change happens in the real restaurant. No shutting down, no chaos, no angry customers.

This is Virtual DOM (used by React, Vue, etc.):

  • Lightweight JavaScript copy of the Real DOM.
  • You make changes here freely and fast.
  • It calculates the minimum changes needed.
  • Then it batches them and updates only what's necessary in the Real DOM.
  • Result? Blazing fast, smooth apps like Facebook, Netflix, or Instagram feel buttery smooth.

More Memorable Real-Life Examples 🧠

Concept Real Life Example Why It Sticks
Real DOM Writing an exam on paper. One mistake? Tear the whole page & rewrite everything. Painful & slow
Virtual DOM Writing on a whiteboard or Google Doc. Edit, erase, compare, then only finalize final version. Quick & efficient
Real DOM Rebuilding an entire Lego city for one missing brick. Overkill
Virtual DOM Keeping a photo of your Lego city, editing the photo first, then only replacing that one brick. Smart!

The Magic Trick: Diffing + Reconciliation ✨

Virtual DOM doesn't just copy — it smartly diffs (compares) trees like a detective:

  1. Creates new Virtual DOM tree after your update.
  2. Compares with previous one.
  3. Finds differences.
  4. Applies only those differences to Real DOM.

1. Initial Render Process in React

The initial render (also called mounting) is the first time React builds the UI for your component tree.

Here's what happens step by step:

  1. ReactDOM.render() / createRoot.render() is called with your root component (e.g., <App />).
  2. React calls your component function (or render() in class components). This is the "render phase".
  3. During this execution:
    • All hooks run in order (useState, useEffect, useMemo, etc.).
    • JSX is converted into React elements (plain JS objects describing what the UI should look like).
  4. React builds the Virtual DOM — a lightweight in-memory representation of the real DOM.
  5. React compares the new Virtual DOM with an empty previous tree (nothing exists yet) and figures out what needs to be created.
  6. Commit phase: React makes the actual DOM mutations (creates nodes, sets attributes, adds event listeners).
  7. After the DOM is updated, useLayoutEffect runs (synchronously), then useEffect (asynchronously).

This is why your first console.log in a component happens before you see anything on screen — rendering and committing are separate.


2. How State or Props Changes Trigger Re-render

React follows a "render on data change" model.

Triggers for re-render:

  • State change (setState, useState setter, Redux dispatch, etc.)
  • Props change (parent re-rendered and passed new props)
  • Context value change (if component consumes that context)
  • Parent re-render (children re-render by default unless memoized)
  • Hooks like useReducer

What actually happens during re-render:

  1. A state/prop update is scheduled.
  2. React starts the reconciliation (diffing) process from the component that changed (and its subtree).
  3. The component function runs again from top to bottom.
  4. New Virtual DOM is created for that subtree.
  5. React diffs the new Virtual DOM with the previous one (fiber tree).
  6. Only the parts that actually changed are updated in the real DOM (thanks to the heuristic algorithm).
  7. Commit phase again → effects.

Important optimizations:

  • React.memo() on functional components
  • useMemo, useCallback
  • React.PureComponent / shouldComponentUpdate
  • Moving state down / lifting state up wisely

Pro tip: Not every state update causes a visible DOM change. React batches updates in event handlers for performance.


Top comments (0)