Does React have Shadow DOM or only Virtual DOM?
sobes.tech AI
Answer from AI
By default, React uses Virtual DOM. Shadow DOM is a separate web components technology.
React uses Virtual DOM to improve the performance of UI updates. Instead of directly manipulating the real DOM on each state change, React creates a lightweight copy of the DOM in memory (Virtual DOM). When changes occur, React compares the current Virtual DOM with the previous one, finds the minimal differences, and updates only the necessary parts of the real DOM.
Shadow DOM, on the other hand, is part of the web components standard and is designed to encapsulate styles and structure within custom elements. It creates a separate DOM tree isolated from the main document.
You can use React together with web components that utilize Shadow DOM, but React itself does not create or use Shadow DOM by default for its components.
// Example of Virtual DOM concept in React
// When the state changes, React compares the VDOM
// and updates only the changed parts of the DOM
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment() {
this.setState({ count: this.state.count + 1 });
// React will update only the text node with the number in the real DOM
}
render() {
return (
<div>
<p>Counter: {this.state.count}</p> {/* This part of the component will be virtualized */}
<button onClick={() => this.increment()}>Increase</button>
</div>
);
}
}
<!-- Example of using Shadow DOM -->
<my-custom-element></my-custom-element>
<script>
customElements.define('my-custom-element', class extends HTMLElement {
constructor() {
super();
const shadowRoot = this.attachShadow({ mode: 'open' }); // Creating Shadow DOM
shadowRoot.innerHTML = `
<style>
p { color: blue; } /* Style encapsulated in Shadow DOM */
</style>
<p>This text is in Shadow DOM</p>
`;
}
});
</script>
Main differences:
| Characteristic | Virtual DOM | Shadow DOM |
|---|---|---|
| What is it? | Concept/pattern in memory | Actual browser technology |
| Purpose | UI update optimization | Style and structure encapsulation |
| Where used? | Frameworks/Libraries (React, Vue) | Web components |
| How it works? | Tree comparison in memory | Creating an isolated DOM tree |