Reconciliation and Diffing in React.

virtual-dom.webp Let me start by explaining the supposedly confusing but simple concept of Diffing which then plays into the understanding of reconciliation in React. so without wasting much of your time blabbering about how inconsistently great "wink wink" my knowledge of the in-depth workings of React is, let's dive into it...

How is React so fast?

This is due to the virtual DOM. Under the hood React maintains a "Virtual" representation of the "Real" DOM. Whenever we make changes to the react app, react renders a virtual DOM which is, like everything else in the JS world - a JavaScript Object!!. React then scans the virtual DOM and the real DOM, when it determines the difference, it goes to the real DOM and only updates the difference.

it actually stops checking when it finds the first difference and updates the entire sub-tree of that node to the real DOM and re-renders.

For this React uses a method called the Diffing Algorithm to compare the old version of DOM to the updated DOM. Diffing is an algorithm based on two assumptions:

  • Two different types of elements will produce different trees.
  • The dev can hint at which child elements will remain stable across renders with a key prop.

The DOM is stored in the form of trees, when diffing the two trees(old and new), React first compares the root elements of both the trees.

  • If the Elements are of different types React will replace the old tree and build a new tree from scratch.

  • If the Elements are of the same types React looks at the attributes of both, whilst keeping the same underlying DOM node and only updating the changed attributes. The component is updated in the next lifecycle.

Stick to it, the end is near

This process of updating the DOM is known as reconciliation, for which react uses the Diffing algorithm. When there is a change in the react app:

  • React creates a virtual DOM and compares it to the real DOM.
  • The comparison is done using the Diffing Algorithm.
  • The entire subtree from the first node where it finds a difference is replaced/updated in the real DOM.
  • The comparison in the DOM trees is done in the BFS(Breath First Search)

    BFS is the process of searching through a tree one level at a time, all the nodes of the level are traversed before moving to the next level, till the search requirement is met.

This is a little peek under the hood as to why react is so fast, to conclude it happens due to the concept of reconciliation which uses the diffing algorithm.