top of page
Search

How Virtual DOM Works?

  • Writer: Titash Roy
    Titash Roy
  • May 30, 2020
  • 2 min read

Updated: Jul 27, 2020

What is DOM? A DOM(Document Object Model) is the programming representation for HTML and XML documents. It can be thought as the data representation of the objects that comprise the content of a document on the web. The DOM represents the document as nodes and objects. This makes it easier for any external API to update/modify specific nodes on the webpage. Below is the pictorial representation of the DOM, where each element in the webpage is represented by an object and each attribute is represented as a property of the object.

See the source image

What is virtual DOM? The virtual DOM (VDOM) is a concept in the front-end development world, where a “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. In simple terms, Virtual DOM is a replica of the actual DOM that is not tightly coupled with the webpage. Like the actual DOM, the VDOM is also a node tree that lists elements and their attributes and content as objects and properties.

Why Virtual DOM(VDOM) is useful? In today’s world, everyone wants everything to be fast. A website/webpage is not an exception. We want the webpage to reflect any change, instantly. This is where VDOM comes into picture. Let’s consider a practical example: Adam gets ready for the office, just before leaving, he notices that his shoes are not well-groomed. So he decides to change his shoes. He changed only his shoes and left for office. This is exactly how a VDOM works. Every clothing element on Adam can be thought of as a component in the DOM structure. In order to change his shoes, he need not change his other clothing parameters. Similarly in VDOM, only the affected component is reloaded(rendered) to reflect the update and the other DOM components are unaffected. How VDOM updates the DOM? React’s render method creates a node tree from React components and updates this tree in response to changes in the data model, caused by any action like an external API call. Also, each time the data model changes in a React app, a new Virtual DOM representation is created and stored in the memory. Updating the real DOM to reflect any change in the data-model, is a three-step process in React. The steps are as follows: 1. Whenever anything has changed, the entire tree node structure will be re-rendered(reloaded) in a Virtual DOM representation. 2.The difference between the previous Virtual DOM representation and the new one will be calculated. 3.The real DOM will be updated with only the difference calculated in step 2. This is just like the practical example, explained a few sections before.

See the source image


Comments


Join my mailing list

Thanks for submitting!

“True originality consists not in a new manner but in a new vision”

  • LinkedIn
  • Facebook
  • Twitter
bottom of page