Sobes.tech
Middle

What is the difference between virtual DOM and shadow DOM?

sobes.tech AI

Answer from AI

Virtual DOM is an abstraction of the real DOM used in libraries like React. It represents a lightweight tree of objects in memory that reflects the UI structure. When the application's state changes, a new virtual tree is created, compared with the previous one (diffing), and only the minimal necessary changes are applied to the real DOM. This improves performance by reducing the number of operations on the real DOM.

Shadow DOM is a web components technology that allows encapsulating part of the DOM and CSS within a component. Elements inside the shadow DOM are isolated from the rest of the page, preventing style and script conflicts. Shadow DOM creates a separate DOM tree nested within an element, but it exists in the real DOM and affects rendering.

In summary:

  • Virtual DOM is an abstract representation of the DOM in memory for UI update optimization.
  • Shadow DOM is a real isolated subtree of the DOM for component and style encapsulation.

Example of using virtual DOM in React:

function Counter() {
  const [count, setCount] = React.useState(0);
  return <button onClick={() => setCount(count + 1)}>{count}</button>;
}

Example of creating shadow DOM:

const host = document.querySelector('#host');
const shadowRoot = host.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = `<style>p { color: red; }</style><p>Shadow DOM content</p>`;