Sobes.tech
Junior

What is DOM and Virtual DOM?

sobes.tech AI

Answer from AI

DOM (Document Object Model) is a programming interface for HTML, XML, and SVG documents. It provides a structural representation of the document as a tree of nodes and defines how programs can access its content, structure, and styles, as well as modify them.

Virtual DOM is a concept that represents a DOM in memory. It is used in libraries and frameworks like React to optimize UI updates.

Comparison:

Feature DOM Virtual DOM
Type API interface for the document In-memory representation of the DOM
Modification Direct manipulation of elements Creating a new tree, comparing with the previous one
Performance Relatively slow with frequent changes Faster with batch updates
Complexity Depends on direct access to elements Abstracts the complexity of DOM updates
Screen update Each change re-renders part of the UI Single batch update after diffing

Virtual DOM process in React:

  1. When the component state changes, React creates a new Virtual DOM tree.
  2. This new Virtual DOM tree is compared with the previous one (diffing process).
  3. The minimal set of changes needed to update the real DOM is calculated.
  4. These changes are batched and applied to the real DOM (reconciliation process).

Example of Virtual DOM concept (simplified):

// Initial Virtual DOM state
const virtualDom1 = {
  type: 'div',
  props: {},
  children: [
    { type: 'h1', props: {}, children: ['Hello1'] }
  ]
};

// New Virtual DOM state after data change
const virtualDom2 = {
  type: 'div',
  props: {},
  children: [
    { type: 'h1', props: {}, children: ['Hello2'] }
  ]
};

// Diffing process (comparing virtualDom1 and virtualDom2) will detect:
// The text inside h1 has changed

// Reconciliation process (applying changes to the real DOM)
// Will update only the text of the h1 element in the browser, not the entire div.
What is DOM and Virtual DOM? — Node.js - sobes.tech