DEV Community

Donny
Donny

Posted on

A Virtual DOM You Say? I Feel ReactJS Coming On!

They say necessity is the mother of invention. So what was the big issue at Facebook a decade ago?

Way back in 2010, Facebook was having a problem with “Cross Site Scripting” attacks. This meant malicious users were putting javascript via the browser onto sites and then using that Javascript to steal information.

But there was a problem with the back-end technology called XHP that Facebook was using to address these attacks. Dynamic web applications such as Facebook require many roundtrips to a server, and XHP did not minimize all these roundtrips to the server. Pages had to re-render over and over again which was expensive in terms of time and bandwidth. In an effort to solve that problem, a Facebook engineer by the name of Jordan Walke asked his boss for 6 months time to come up with a way to take XHP out of the backend and into the browser using Javascript. The result was a faster application he called “FaxJS”, later to be known as ReactJS

How does React make an application run faster? One important way is through use of the virtual DOM.
The virtual DOM is not the same as the DOM used in vanilla Javascript and Jquery. The virtual DOM is a lightweight copy of the regular DOM. Think of it this way: if the regular DOM were a house, then the virtual DOM would be the house’s blueprint.

The way the virtual DOM works is this. When you render a JSX element, each and every virtual DOM object gets updated. But wait, doesn’t this sound like it will take a lot of time? Not really because the time the virtual DOM takes to update is very small.

Once the virtual DOM is updated, React compares the virtual DOM with a virtual DOM snapshot taken right before the update.

By comparing the new virtual DOM with a pre-update version, React will know exactly which virtual DOM objects must be changed. This process is called “diffing.”

Once React knows which virtual DOM objects have to be changed, it will update those objects only. React will not touch those objects that have not changed.

This innovation of updating only the necessary parts of the DOM is what gives React a reputation for performance.

So here’s a summary of what happens when you update the DOM in React:

The entire virtual DOM gets updated
The virtual DOM gets compared to the selfie it took right before the update.
Only the changed objects get updated on the real DOM. If an object was not altered, React won’t touch it!
Changes on the real DOM cause the screen to change.

*By the way......

Why is React called React? React was developed for Facebook, an app that has constantly changing data. React is a front-end framework or the “View” in MVC architecture. This means that as the user clicks around and changes the app’s view, the view should “react” or change quickly with those user events.

Keep on coding out your dreams!

Top comments (0)