1/3
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
What is the Virtual DOM?
The Virtual DOM is an in-memory representation of the real DOM. Frameworks like React build a lightweight tree of elements in JavaScript, then compare it to the previous version using a diffing algorithm. Instead of re-rendering the whole page, only the changed nodes are updated in the real DOM, which improves efficiency and performance.
Why is the Virtual DOM faster than directly manipulating the real DOM?
Direct DOM operations are expensive because they cause reflows and repaints in the browser. The Virtual DOM batches changes in memory first, calculates the minimal set of real DOM updates needed, and then applies them all at once. This reduces layout thrashing and speeds up rendering for dynamic UIs.
How does the diffing algorithm work in React’s Virtual DOM?
React compares the old Virtual DOM tree to the new one, node by node. If elements differ, it marks them for update. By default, it uses keys to optimize list rendering, so only the changed items re-render instead of the whole list. This heuristic makes diffing roughly O(n) rather than re-rendering everything.
What role do keys play in the Virtual DOM?
Keys uniquely identify elements in a list. Without keys, React may re-use or misorder components, causing bugs or unnecessary re-renders. With stable keys, React quickly matches old and new elements, only updating what’s truly changed, which improves performance and predictability.