DEV Community

eliastooloee
eliastooloee

Posted on

What is a virtual DOM, and why do we utilize it so frequently when building modern single page applications?

What is a DOM?
Let’s start with the basics. A Document Object Mode, or DOM, is a programming interface through which HTML and XML can interact with programming languages like Javascript. It represents the document as a collection of nodes and objects, allowing object oriented languages to interact with it. It is what it says on the can.

What is a virtual DOM?
A virtual DOM (VDOM Henceforth) is also what it says on the can. It is an abstraction of the DOM, detached from a browser specific interface, where changes in state can be made without changes to the actual user interface.

Why is a VDOM helpful? How is it any different if it's just a representation of a DOM?
A traditional HTML DOM is arranged as a tree, with tags acting as objects. Nested tags are children of the enclosing tags. Inner text is also an object and is a child of its tags. This arrangement means that after an update a tag and all of its children must be re-rendered, which is costly, particularly for large apps with enormous trees.
A VDOM works similarly to a DOM. When elements are changed in the UI a VDOM is created as a tree, with each element represented as a node. If the state of an element changes, a new VDOM tree is created. The VDOM trees are then compared, and the optimal method to make changes in the DOM calculated. At this point the DOM is re-rendered.
Pre-planning changes to the DOM avoids the expensive operations of needlessly re-rendering elements in the DOM tree. This is the primary advantage of the VDOM over the DOM. Think of it like going to the grocery store. You could just wander around, throwing things you need into your cart, but it would be slow. If you instead made a detailed list, pre-determined the locations of the list items in the grocery store, and calculated an optimal route ahead of time, you’d be done shopping much faster. That’s the VDOM. It’s the faster way of doing things.

Top comments (0)