How Vue works inside
Vue wraps your state in a Proxy. When an effect (a render, a computed or a watch) reads a property, Vue tracks it; when the property changes, Vue triggers the effects that read it. Updates go into a queue and run once in the next microtask, so many changes cause one render, and nextTick waits for that render. The compiler marks the parts of a template that can change, so updates skip the static parts.
Author: bezzad
Contents
Why learn the inside?
Senior interviews often ask “how does Vue know what to update?” The answer also explains real bugs in our shop:
- After adding a product, the code scrolls to the end of the list, but it scrolls to the old end.
- The product table with 20,000 rows is slow, even when only the filter text changes.
- A destructured value stops updating (you saw this in the fundamentals lesson).
All three come from how reactivity and the update queue work.
Proxy, track and trigger
// A very small model of Vue's idea. Not the real code.
let activeEffect: (() => void) | null = null;
const deps = new WeakMap<object, Map<PropertyKey, Set<() => void>>>();
function reactive<T extends object>(target: T): T {
return new Proxy(target, {
get(obj, key, receiver) {
track(obj, key); // remember: the active effect reads this key
return Reflect.get(obj, key, receiver);
},
set(obj, key, value, receiver) {
const ok = Reflect.set(obj, key, value, receiver);
trigger(obj, key); // run again what read this key
return ok;
},
});
}
- reactive() returns a Proxy around your object. The object itself is not changed.
reactive(obj) !== obj, and toRaw gives the original back. - An effect is a function that Vue runs and watches: the render of a component, a computed, a watch, a watchEffect.
- While an effect runs, every get calls track: “this effect depends on this object and this key”.
- Every set calls trigger: “find the effects that depend on this key and schedule them”.
- Tracking happens again on every run. If a branch is not taken (
v-ifis false), its values are not tracked, so changing them does not cause a render. - ref works the same way with a
.valuegetter and setter. That is why a ref works with any value, even a number, and why you need.valuein script. - Destructuring reads the value once and copies it. The copy is a plain value with no getter, so no track. This is bug 3. Use toRefs or read through the object.
- Vue 3.5 rewrote the inside (version counters and linked lists) to use less memory and run faster. The idea, track on read and trigger on write, is the same.
computed is lazy and cached
- A computed does not run when it is made. It runs the first time someone reads
.value. - It remembers the result. When a dependency changes, it is only marked dirty. It runs again on the next read.
- Since Vue 3.4, if a computed runs again and returns the same value, the effects that read it are not triggered.
- So use computed for derived values, and keep it pure: no requests, no changing other state.
The update queue and nextTick
async function addProduct(p: Product) {
products.value.push(p);
count.value++;
lastAdded.value = p.id;
// The DOM is still the old one here.
await nextTick();
listEl.value!.lastElementChild!.scrollIntoView();
}
- A change does not render at once. trigger puts the component’s update job into a queue. A job is in the queue only once, even if many values change.
- The queue runs in a microtask, after your current code ends. Three changes give one render.
- So right after a change, the DOM is old. nextTick() returns a promise that resolves after the queue has run. This fixes bug 1.
- Parents update before children, because jobs are sorted by component id (parents are made first).
- A watch callback runs before the render by default (flush: ‘pre’). Use
flush: 'post'(or watchPostEffect) if the callback needs the new DOM.flush: 'sync'runs at once on every change; use it rarely.
The compiler helps the runtime
Vue templates are compiled to render functions. The compiler knows which parts can change:
<template>
<div class="card">
<h2>Our products</h2>
<p>{{ product.name }}</p>
<button :class="{ active: inCart }">Add</button>
</div>
</template>
- The h2 is static. It is made once (hoisted) and never compared again.
- The p has a patch flag that says “only the text can change”. The button’s flag says “only the class can change”. On update, Vue checks only those things.
- A block collects all dynamic nodes of a template in a flat list, so Vue does not walk the whole tree. Only v-if and v-for start new blocks.
- This is why templates are usually faster than hand-written render functions: the compiler adds these hints for you.
- Vapor mode is a new way to compile components to direct DOM code without a virtual DOM. It is being added in Vue 3.6; check its status before you use it.
Big data: shallowRef and markRaw
A deep reactive array of 20,000 product objects makes a Proxy for every object you read and tracks every property. That costs memory and time (bug 2).
const products = shallowRef<Product[]>([]);
async function load() {
products.value = await api.getProducts(); // one change, one trigger
}
function rename(id: number, name: string) {
// Replace the array, do not change inside it.
products.value = products.value.map((p) => (p.id === id ? { ...p, name } : p));
}
- shallowRef tracks only
.value. The objects inside are plain. Changingproducts.value[0].namedoes not render anything. - To update, replace the value (immutable style), or call triggerRef after a change inside.
- markRaw tells Vue never to make an object reactive. Use it for class instances from libraries, like a map or a chart object.
- For a long list, render only the visible rows (a virtual list). Reactivity is not the only cost; 20,000 DOM rows are slow too.
- Measure first with Vue DevTools and the browser profiler. Do not make everything shallow “to be safe”.
Common mistakes
| Mistake | Result | Better way |
|---|---|---|
| Reading the DOM right after a change | Old size, old position. | await nextTick(), or watch with flush post. |
| Destructuring a reactive object | The copy never updates. | toRefs, or read through the object. |
| Requests or writes in a computed | Hidden effects, loops, extra calls. | computed is pure; use watch for effects. |
| Deep reactive for huge read-only data | Slow and uses a lot of memory. | shallowRef or markRaw, and a virtual list. |
| flush sync watchers everywhere | Many runs, no batching. | Keep the default pre flush. |
| Comparing reactive(obj) to obj | Never equal. | Compare with toRaw, or compare ids. |
Summary in 6 lines
- reactive and ref use getters and setters (a Proxy for objects). Reading tracks, writing triggers.
- Effects are renders, computeds and watchers. Their dependencies are tracked again on every run.
- computed is lazy and cached, and must be pure.
- Changes are batched: the update job runs once in the next microtask. nextTick waits for it.
- The compiler hoists static parts and adds patch flags, so updates check only what can change.
- For big data use shallowRef or markRaw, replace values instead of changing them, and measure first.