React & Modern Frontend (445 Qs)•Part 1: Core React, JSX & Component Architecture (1 - 77)
What is the difference between Shadow DOM and Virtual DOM?
The Shadow DOM is a browser technology designed primarily for scoping variables and CSS in web components. The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs.
The key differences in a table format shown below:
| Feature | Shadow DOM | Virtual DOM |
|---|---|---|
| Purpose | Encapsulation for Web Components | Efficient UI rendering |
| Managed by | Browser | JS frameworks (e.g., React) |
| DOM Type | Part of real DOM (scoped) | In-memory representation |
| Encapsulation | Yes | No |
| Use Case | Web Components, scoped styling | UI diffing and minimal DOM updates |
Practical Code Example
javascript
// 1. Shadow DOM: Browser standard for scoping encapsulated CSS & DOM subtrees (Web Components)
const host = document.querySelector('#host');
const shadowRoot = host.attachShadow({ mode: 'open' });
shadowRoot.innerHTML = '<style>p { color: red; }</style><p>Shadow DOM</p>';
// 2. Virtual DOM: In-memory JavaScript object graph used by React for fast diffing.