💚 Vue.js Intermediate

What is Vue's virtual DOM and how does the diffing algorithm work?

Answer

Vue's Virtual DOM (VDOM) is an in-memory JavaScript representation of the actual DOM. When component state changes, Vue re-renders the component template to produce a new virtual DOM tree, then diffs it against the previous tree and patches only the changed parts of the real DOM. VDOM node (VNode): a plain JavaScript object describing a DOM node: { type: "div", props: { class: "card", onClick: handler }, children: [{ type: "span", props: {}, children: "Hello" }] }. Diffing algorithm: Vue's diff compares old and new VNode trees with these heuristics: (1) Nodes of different types (div → span) → completely replace; (2) Same type nodes → update props/attributes in place; (3) Children diffing: without keys — simple sequential comparison (may produce incorrect results with stateful nodes), with keys — uses a "longest increasing subsequence" algorithm to minimize moves. Vue 3 optimizations (Compiler-informed): Vue 3's template compiler analyzes templates at compile time and adds hints: (1) Static hoisting: static nodes (no bindings) are lifted out of the render function — created once, reused; (2) Patch flags: nodes with dynamic content get a flag indicating WHAT is dynamic (CLASS, STYLE, PROPS, TEXT) — only those parts are diffed at runtime; (3) Block tree: only tracks dynamic children in stable structural blocks. These optimizations make Vue 3's runtime patching significantly faster than runtime-only diff algorithms (React).