What is the difference between virtual DOM and DOM?

Nowadays the term 'virtual DOM' introduced by React is very popular among developers. I just want to understand what is virtual DOM and the benefits of using it in place of simple DOM.

1 Answers

DOM stands for Document Object Model and is known as HTML code among web developers. The elements included inside HTML are called nodes and are tree-structured. You can manipulate these nodes with the help of javascript. But it will not update that much quicker if your node structure is too large. For example, if there is a node element in HTML that has id 'container' and you want to change its background, you can use the below code for that purpose.

document.getElementById('container').style['background'] = "#ffffff";

There are performance issues related to it as you have to find the required node from the whole node tree. If you are creating SPA (Single Page Application) using javascript, it will have a large DOM tree and there will be a lot of problems to update and apply events on the required node elements. It will also hard to manage events and elements update. This is also not sufficient if you are doing it manually and will reduce the performance of the application. The solution to this problem is virtual DOM which is used by several javascript frameworks like React.

Well Virtual DOM was not introduced by React but it is using Virtual DOM and provide us elements that can be helpful to create Virtual DOM. Virtual DOM is a programming technique where virtual UI is kept into memory and it is synced with DOM. React uses a library called 'ReactDOM'  for the synchronization process.

Virtual DOM can also be called as an abstraction of real DOM. React do all the computations and update its Virtual DOM. This will skip the real DOM operations which is slow and browser-specific.

In React, we use React Elements to make our Virtual DOM. React Elements are immutable so these are fast and provide great performance when it comes to updating these elements and applying events.

Never leave your website again in search of code snippets by installing our chrome extension.