Diffing in React

This is what makes React super fast

Let's first understand what DOM is.

DOM stands for Document Object Model and it is this concept that has bestowed upon JavaScript the ultimate power to generate dynamic HTML elements and interact with them.

The HTML DOM is a standard object model and programming interface for HTML. Whenever a webpage loads, the browser creates something called an HTML DOM tree of the page. The DOM tree consists of all the HTML elements and their properties in a hierarchy.

image.png

For the above example, the DOM would look something like this:

Untitled Diagram(1).png

Simple right? So let's say we want to update the text from "Rock and Roll" to "Rock and roll with React", then the entire page gets rendered again to incorporate that change in the DOM tree. Now imagine the amount of overhead in reloading again and again for every minor change in the webpage. Ugh! Not cool at all.

So now what the heck is Virtual DOM ?

Well, it's a virtual form of the DOM just like virtual reality. Something which is there, but is not. And this is truly what makes React so powerful.

React makes a virtual DOM, which is basically an exact copy of the original DOM. Whenever an update is made, React compares its virtual DOM with the original DOM and upon detecting the updated node, it only updates that node in the original DOM.

In the above example, let's say Section is a React.Component. Now in case, if we change the text inside the p tag, only this component will be re-rendered in the original DOM instead of the entire page. That means only the text node for this tag will be updated in the DOM tree. And any guesses what triggers this in the code ? If you guessed, render() then you deserve a slice of pizza today.

To make it more clear, when we render a JSX element every single virtual DOM object is updated. After updating, React then compares this virtual DOM with the snapshot of the virtual DOM taken right before the update. This process of finding the exact objects to be updated is called Diffing. This includes the text node values, the attribute values and even the style properties. Once React figures out that it only re-renders that particular object(s) in the original DOM. Isn't that awesome!

That's what makes React an ideal choice for developing Single Page Applications and Progressive Web Apps. The Diffing Algorithm allows React to keep up with high-performance apps and make the user interaction a truly seamless one.