Interview question
What is Virtual DOM and why is it important? Virtual DOM क्या है और यह महत्वपूर्ण क्यों है?
Answer
Virtual DOM is an in-memory representation of the real DOM. React uses it to efficiently update the UI by comparing changes (diffing) and updating only what changed.
// How Virtual DOM works:
// 1. React creates Virtual DOM representation of UI
// 2. When state changes, new Virtual DOM is created
// 3. React compares (diffs) old and new Virtual DOM
// 4. React updates only the changed parts in real DOM
// Example
function Counter() {
const [count, setCount] = React.useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// When button is clicked:
// 1. count state changes
// 2. Component re-renders
// 3. New Virtual DOM is created
// 4. Old and new Virtual DOM are compared (diffing algorithm)
// 5. React finds that only <p> needs update
// 6. Only <p> tag is updated in real DOM (not the whole component)
// Benefits of Virtual DOM:
// 1. Performance: Batch updates, minimize real DOM manipulation
// 2. Abstraction: Developers don't need to worry about DOM details
// 3. Cross-platform: Virtual DOM enables React Native
// 4. Easier debugging: Predictable updates
// Reconciliation (diffing algorithm)
const oldVDOM = { type: 'div', children: [{ type: 'p', text: 'Count: 0' }] };
const newVDOM = { type: 'div', children: [{ type: 'p', text: 'Count: 1' }] };
// React finds minimal changes and updates real DOM efficientlyVirtual DOM एक in-memory representation है real DOM का। React efficiency के लिए इसे use करता है।
Virtual DOM advantages:
1. Performance: Batch updates से real DOM को कम manipulate करते हैं
2. Efficient diffing: सिर्फ changed parts update होते हैं
3. Abstraction: Developers को DOM details से concern नहीं
4. Faster rendering: Batch updates से faster
Process:
1. State/Props change
2. New Virtual DOM create होता है
3. Old vs new compare होता है (diffing)
4. केवल changed parts को real DOM में update करते हैंWas this answer clear?