Inside React.JS | Virtual DOM

The chasm between DOM and Virtual DOM

Lakshitha Wisumperuma
The Startup
5 min readNov 1, 2020

--

Photo by RKTKN on Unsplash

React.js is a well known JavaScript library for building user interfaces. According to Stackoverflow data for 2020, React ranked the second most popular web frameworks among professional developers. While setting aside talking about fundamental features in React like JSX, states and props, component life cycle, higher-order components or hooks let’s take a step back and look at a feature that makes React efficient. The Virtual DOM.

The DOM

Before we dive into Virtual DOM in React let’s try to understand what’s DOM and why we use it. MDN Web docs have a decent explanation defining what DOM is,

“The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects. That way, programming languages can connect to the page.”

-MDN Web Docs

Consider a scenario where we open a HTML file through our browser, the browser creates a tree-like structure from given HTML code known as DOM. Each point and intersection on this tree is known as a DOM Node. Everything is a node, from the innermost text to the document itself everything on the DOM is a node, like HTML elements, HTML attributes, plain texts, comments, tab characters etc.

Figure 1.1 | Source: TutorialsTonight

Figure 1.1 shows basic interpretation of a DOM. If you’ve written JavaScript, chances are you’ve heard of the DOM and interacted with it. When you use JavaScript or any language for that matter to perform a certain task on a web page, the JavaScript you’ve written needs a way to interact with the HTML and other documents that make up your web page. JavaScript does this through DOM and DOM scripting, JavaScript gets all the power it needs to create dynamic HTML.

consider the following HTML code example:

If we map the above to a DOM structure we get:

Figure 1.2

However, as Creator of jQuery once said,

The DOM is a mess. — John Resig

Updating the DOM isn't much of a problem with simple sites but when it’s about complicated websites, managing and making changes to the DOM can quickly become a challenge to developers. When multiple scripts need access to multiple DOM objects, maintaining a consistent state of the DOM requires all kinds of manipulations and checks, and some things you might want to do are downright impossible. Eventually making the updating of the DOM inefficient. *Enters Virtual DOM*

The Virtual DOM

Now that you know use case of DOM, lets now look more into Virtual DOM. What if instead of rendering all these changes into the real DOM, we apply them to a lightweight virtual DOM, which doesn't get rendered in real life making changes cheap and also batch changes together instead of sending updates for every single change in state to make it more efficient? That is what Virtual DOM is, a tree data structure in a plain JavaScript object which exists in memory. It should also be noted that since full in-memory copy of the DOM, this could lead to high memory use depending on the code complexity.

The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM. This process is called reconciliation.

-ReactJS Docs

React creates a new version of DOM which is known as the React virtual DOM. When you write React code, you’re making changes to the virtual DOM, not the real DOM. When a user clicks a button or enters a value, or simply makes a change in an element in a React component, React compares the state of the virtual DOM to the real DOM. If they’re the same, React doesn’t need to do anything. If they’re different, React updates the real DOM to match the virtual one.

Figure 1.2 | Stackoverflow

Template language (JSX) tells the template compiler to build an in-memory DOM tree, where render() function creates a virtual DOM tree of reactElements. At any given point there are two trees in memory which reconcile and render the real DOM.

Consider the following scenario,

and then consider the following scenario,

Only difference is adding className right? It makes sense to identify that change and render right? This is what React does at a high level. It does a “diff” between two render passes and applies the minimal changes needed to reflect the new render tree.

Diffing Algorithm / Reconciliation

Finding the minimum number of modifications required is an o(n³) complexity problem which means it would take 1000 comparisons to display 10 elements. However Reacts uses a diffing Algorithm of the order O(n) which involves a heuristic approach based on two assumptions,

  1. Two elements of different types will produce different trees, react will not attempt to diff them but replace completely, Breadth-first traversal, where we go level by level.
  2. Child elements may be hinted as stable across renders with a “key”, to optimize performance, keys should be stable, predictable and unique.

Currently React is looking into a new diffing implementation where instead of traversing the DOM recursively, it uses a new data structure called a Fiber (new reconciliation engine in React 16), which is a plain JavaScript object that keeps track of parent-child node relationships as a singly-linked list, called incremental render or scheduling.

Although there is still a lot happening behind the scenes, this is one important concept that would be helpful for you as a React developer to start understanding the core of React and how it actually works.

Feel free to pass down any suggestions or questions you have.

Until next time 😃

--

--