All Articles

What is the difference between dom and virtual dom

Jul 6, 2022

What is the DOM?

DOM stands for Document Object Model and is a programming interface for web documents. It defines the logical structure of documents and the way a document is accessed and manipulated. Elements of HTML become nodes in the DOM.


	      <td>Shady Grove</td>
	      <td>Over the River, Charlie</td>        

The DOM provides an interface (API) to traverse and modify the nodes. We can use different programming languages communicate with the method exposed by the DOM but web developers usually use JavaScript. Some example of methods are “getElementById” or “createElement”

	 const heading = document.createElement("h1");
	 const text = document.getElementById("content");

Issues with the DOM

The HTML DOM is always tree-structured and this is great because we can traverse trees fairly easily. Unfortunately when the dom grows, modifying it becomes less and less efficient and slow.

With the arrival of new javascript frameworks and Single Page Applications, we need to modify the DOM tree incessantly and a lot.

React try to help in two ways: - Declarativeness: instead of traversing the DOM tree manually, you simple declare how a component should look like and React does the low-level job for you (the HTML DOM API methods are called under the hood) - Virtual DOM: is an abstraction of the HTML DOM. It is lightweight and detached from the browser-specific and helps to solve the performance issues.

What is Virtual DOM?

The Virtual DOM is a lightweight JavaScript representation of the DOM, you can think about it like a simplified copy of the HTML DOM.

It allows React (and other declarative frameworks) to do its computations within this abstract world and then synch with the “real” DOM. Updating the virtual DOM is infact faster than updating the actual DOM.

In summary, this is what happen when you update a component:

  1. The virtual DOM gets updated.
  2. The virtual DOM gets compared to a previous virtual DOM snapshot to figures out exactly which objects have changed (this process is called “diffing”).
  3. Only the changed objects get updated on the real DOM.
  4. Changes on the real DOM cause the screen to change.