My account

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.

Not reviewedWritten with AI helpReading time: 17 minOnline shop exampleVue 3.5

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:

  1. After adding a product, the code scrolls to the end of the list, but it scrolls to the old end.
  2. The product table with 20,000 rows is slow, even when only the filter text changes.
  3. 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

Read: trackRender effectreads cart.totalProxy gettrack(cart, total)deps of totalrender, computedWrite: triggerYour codecart.total = 120Proxy settrigger(cart, total)Update queuerender jobOnly effects that read totalTracked again on every run
When a render or a computed reads cart.total, the Proxy's get trap tracks it: the property now has a list of effects that depend on it. When code sets cart.total, the set trap triggers those effects, and they go into the update queue.
// 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;
    },
  });
}
  1. reactive() returns a Proxy around your object. The object itself is not changed. reactive(obj) !== obj, and toRaw gives the original back.
  2. An effect is a function that Vue runs and watches: the render of a component, a computed, a watch, a watchEffect.
  3. While an effect runs, every get calls track: “this effect depends on this object and this key”.
  4. Every set calls trigger: “find the effects that depend on this key and schedule them”.
  5. Tracking happens again on every run. If a branch is not taken (v-if is false), its values are not tracked, so changing them does not cause a render.
  6. ref works the same way with a .value getter and setter. That is why a ref works with any value, even a number, and why you need .value in script.
  7. 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.
  8. 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

  1. A computed does not run when it is made. It runs the first time someone reads .value.
  2. It remembers the result. When a dependency changes, it is only marked dirty. It runs again on the next read.
  3. Since Vue 3.4, if a computed runs again and returns the same value, the effects that read it are not triggered.
  4. So use computed for derived values, and keep it pure: no requests, no changing other state.

The update queue and nextTick

Your code (same tick)products.value.push(p)count.value++lastAdded.value = p.idread the DOM here: oldQueue1 update jobMicrotask1 renderafter nextTick: newTime3 changes, 1 render
Three changes in the same tick do not cause three renders. The component's update job goes into the queue once and runs in the next microtask. Code right after the change still sees the old DOM; after await nextTick(), the DOM is updated.
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();
}
  1. 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.
  2. The queue runs in a microtask, after your current code ends. Three changes give one render.
  3. So right after a change, the DOM is old. nextTick() returns a promise that resolves after the queue has run. This fixes bug 1.
  4. Parents update before children, because jobs are sorted by component id (parents are made first).
  5. 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>
  1. The h2 is static. It is made once (hoisted) and never compared again.
  2. 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.
  3. 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.
  4. This is why templates are usually faster than hand-written render functions: the compiler adds these hints for you.
  5. 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));
}
  1. shallowRef tracks only .value. The objects inside are plain. Changing products.value[0].name does not render anything.
  2. To update, replace the value (immutable style), or call triggerRef after a change inside.
  3. markRaw tells Vue never to make an object reactive. Use it for class instances from libraries, like a map or a chart object.
  4. 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.
  5. 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

  1. reactive and ref use getters and setters (a Proxy for objects). Reading tracks, writing triggers.
  2. Effects are renders, computeds and watchers. Their dependencies are tracked again on every run.
  3. computed is lazy and cached, and must be pure.
  4. Changes are batched: the update job runs once in the next microtask. nextTick waits for it.
  5. The compiler hoists static parts and adds patch flags, so updates check only what can change.
  6. For big data use shallowRef or markRaw, replace values instead of changing them, and measure first.

Done reading this lesson?Mark it as finished so it shows in your lessons list and report card.