What is DOM diffing?
DOM, also known as the Document Object Model, is a programmatic representation of the contents of a web page. In other words, the content of a web page is represented in the form of
DOM acts as an API (Application Programming Interface) to modify the structure as well as the content of a web page.
Here's the visualization of the above DOM tree:
Snippet taken from DOM Visualizer by @bioub
These filled circles represent either a DOM element or a DOM node. DOM can be accessed using the
Document API which exposes a global
// test this in browser dev tools' console
// logs `object`
Painting of DOM
Whenever you update your HTML markup, the DOM gets updated and it needs to be repainted or re-rendered in order to reflect the changes on the screen.
// process of browser rendering
DOM tree => CSSOM tree => Render tree => Prepare Layout => Paint Screen
These repaints can be expensive and lead to performance issues. Repainting can happen more often if the user is interacting with the website because of the site being highly interactive.
Virtual DOM & Comparision of DOMs
In order to tackle the issue of expensive rendering, some frontend libraries such as React, create a virtual DOM which is similar to the actual DOM but it's efficient because it doesn't have to be painted.
The virtual DOM is created on every state change or re-render in React and is then compared to the previously created virtual DOM. This process of comparing consecutive instances of virtual DOM is known as
If the virtual DOM is different than the previous one, React will calculate which parts of the DOM have been modified and it will update only those parts in the actual DOM.
If there's no change, the actual DOM will remain untouched. You can explore more about the diffing algorithm in react by visiting their documentation.
Want to implement DOM diffing in vanilla JS? You can.