Virtual DOM in React

Author - Venkat

About this article - Description


Virtual DOM in React

  • Reconciliation
  • React Fiber
  • Diffing Algorithm
  • How render works in React?

What is DOM?

Document Object Model aka DOM is how the browser represents the web page. It is a tree-like structure where each node represents a element.

Javascript provides an API to manipulate the DOM. If we want to change something in the DOM, we can use the API to do so. But, manipulating the DOM is expensive and slow. Because, every time we change the DOM, the browser has to repaint the page and reflow the layout. This is where Virtual DOM comes into play.

Virtual DOM

React creates a virtual representation of the actual DOM. It is exactly like the actual DOM but it is a lightweight copy of the actual DOM it is an in-memory object.

Virtual DOM flow

  1. First time when the component is rendered, React creates a virtual DOM tree.
  2. If state change happens, React creates a new virtual DOM tree instance.
  3. React compares the new virtual DOM tree with the old virtual DOM tree. This process is called Reconcialiation. In this process, React uses a diffing algorithm to find the difference between the two virtual DOM trees.
  4. Once the differences are found, React updates the actual DOM with the changes.

Advantages of Virtual DOM

  1. Since, Virtual DOM is not traversing through the whole DOM tree, it is faster.
  2. React can batch multiple updates and update the actual DOM in a single go.
  3. React only updates the part of DOM that has changed. On the other hand, the actual DOM has to traverse through the whole tree to find the changes and update the DOM.

React never ever manipulates the DOM directly. Instead, it uses the Virtual DOM to update the actual DOM.

Reconciliation

Reconcialiation is the process of updating the DOM tree with minimum number of changes. On changes occurs react creates a new virtual dom and compares it with the old dom instead of directly updating. This process is done with the help of diffing algorithm.

There are three phases

  1. Virtual DOM
  2. Diffing Algorithm
  3. Commit Phase

Diffing Algorithm

The diffing algorithm in react determines the minimum number of changes needed to update the DOM efficiently when a component's state or props changes.

How render works in React?

React follows a two-phase approach when rendering components

  1. React Render Phase (Reconcialiation)
  • React calls the react component functions and creates the virtual DOM
  • It compares the new Virtual DOM with Previous Once
  • React prepares the changes but doesn’t apply them to the real DOM yet.
  1. Commit Phase
  • React updates the real DOM,
  • React runs the lifecycle methos (useEffect()),
  • React paints the updated UI on browser.