How Virtual-DOM and diffing works in React

Understand how DOM is build

From Mozilla —

Understanding the Virtual-DOM

How DOM looks after initial rendering
Component Tree structure build by React

Let us add two numbers and hit the Add button to understand further

Input 1: 100
Input 2: 50
Output : 150

So what happens when you hit the Add button?

<button id="add" onClick={ () => {
IntegerA = parseInt(ReactDOM.findDOMNode(this.refs.input1).value)
IntegerB = parseInt(ReactDOM.findDOMNode(this.refs.input2).value)
IntegerC = IntegerA+IntegerB

Marking the component dirty.

Calculator component marked Dirty
//ReactUpdates.js  - enqueueUpdate(component) function

Traversing the Component lifecycle.

Calculator Wrapper
var flushBatchedUpdates = function () {
while (dirtyComponents.length || asapEnqueued) {
if (dirtyComponents.length) {
var transaction = ReactUpdatesFlushTransaction.getPooled();
transaction.perform(runBatchedUpdates, null, transaction);
if (this._pendingStateQueue !== null || this._pendingForceUpdate) {
this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context);

From Steps 4,5 and 6, we only use render()

Render is where the Virtual DOM gets re-build and the diffing happens

Rendering the Component — Updating the Virtual-DOM, running the diffing algorithm and updating the actual DOM

var prevRenderedElement = this._renderedComponent._currentElement;
var nextRenderedElement = this._instance.render(); //Calculator.render() method is called and the element is build.
Component render() — updating the Virtual DOM, running the diffing algorithm and finally updating the DOM

I may have missed a few steps knowingly or unknowingly, but this diagram covers most of the key steps.

Rendering of the Actual DOM

Only output is re-painted





Web developer | React | Nodejs | GraphQL | Angular 1.X

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Javascript Some important property

An Overview on the 4 Main Principles of Object Oriented Programming

Bitmap Holes Count Using Typescript/JavaScript

Understanding Scope in context of JavaScript

Handling Angular environments in continuous delivery

Function composition point-free style

NumPy 2D array

How to Work with Forms, Inputs and Events in React

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gethyl George Kurian

Gethyl George Kurian

Web developer | React | Nodejs | GraphQL | Angular 1.X

More from Medium

ES Lint “react-hooks/exhaustive-deps” infinite loop potential solution

What’s new in React 18?!

React Concepts

React JS for Beginners