Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 87 ยท Reactivity Fundamentals

How Reactivity Works

Look inside Vue 3 reactivity - proxies, track and trigger, the dependency graph, a working mini reactive system in plain JavaScript, plus shallowRef, triggerRef and markRaw.

You can use ref, computed and watch for months without knowing how they work. Then one day a value stops updating, or a huge list makes the page crawl, and the only way forward is to understand the machinery. The good news: the core idea of Vue's reactivity fits in about forty lines of JavaScript, and in this lesson you will write it yourself.

Everything here builds on Reactive State with ref, reactive Objects, computed and watchers. You do not need Vue to follow the first half; the mini system uses plain JavaScript only.

The problem reactivity solves

Look at this ordinary JavaScript:

JavaScript
let price = 5;
let quantity = 2;
let total = price * quantity; // 10

price = 8;
console.log(total); // still 10

total was calculated once. JavaScript has no idea that it depends on price. A reactive system needs to answer two questions:

  1. Who read this value? (so it knows who to tell)
  2. When was it written? (so it knows when to tell them)

Vue answers the first by intercepting reads and the second by intercepting writes. The tool for intercepting is the JavaScript Proxy.

Proxies: a hook on every read and write

A Proxy wraps an object and lets you run code when a property is read (get trap) or written (set trap). The wrapped object is called the target.

JavaScript
const target = { count: 0 };
const proxy = new Proxy(target, {
  get(obj, key, receiver) {
    console.log("read", key);
    return Reflect.get(obj, key, receiver);
  },
  set(obj, key, value, receiver) {
    console.log("write", key, value);
    return Reflect.set(obj, key, value, receiver);
  }
});

proxy.count;      // read count
proxy.count = 1;  // write count 1

This is how reactive() works. It returns a proxy of your object. The proxy is a different object from the original, so reactive(obj) !== obj. Writing to the original, un-proxied object bypasses all tracking, which is why a reactive object must always be used through its proxy.

A proxy cannot wrap a primitive such as a number. That is the reason ref() exists: it returns a small object with a value property whose getter and setter do the same tracking and triggering. The .value you type is the price of intercepting a primitive.

Track and trigger

Two functions do the real work:

  • track(target, key) is called by every get. If an effect (a render function, a computed getter, a watcher) is currently running, it records "this effect depends on target.key".
  • trigger(target, key) is called by every set. It looks up the effects that depend on target.key and runs them again.

The records live in a structure that is, conceptually, a three-level map:

flowchart LR
    W["WeakMap<br/>target object"] --> M["Map<br/>property key"]
    M --> S["Set<br/>effects that read it"]

For each reactive object, each property has its own set of subscribed effects. This is the dependency graph.

Because the outer map is a WeakMap, an object that nothing else references can be garbage collected together with its dependency records.

The lifetime of one update looks like this:

flowchart TD
    A["Effect starts, becomes the active effect"] --> B["Effect reads state.price"]
    B --> C["get trap calls track: effect added to the price set"]
    C --> D["Later: state.price = 8"]
    D --> E["set trap calls trigger"]
    E --> F["Effects in the price set run again"]

An effect subscribes by reading and is re-run when what it read is written.

Build a mini reactive system

Here is a complete working version. It has reactive, effect, track and trigger, and one important extra: before an effect re-runs, it forgets its old dependencies, so only what it reads on the latest run counts. The page shows how many effects are subscribed to each property after every action.

A mini reactive system in plain JavaScript

At first the effect has read price, qty and showTax, but not tax, because the if branch was skipped. The subscriber line shows price: 1 | qty: 1 | showTax: 1 | tax: 0. Pressing Tax changes tax, yet nothing runs, since nobody depends on it. Press Toggle showTax: the effect runs again, this time reads tax, and tax: 1 appears. Now Tax triggers a re-run.

This is exactly why Vue can re-collect dependencies on every run: a computed or a render function that takes a different branch stops listening to values it no longer uses.

What real Vue adds

The mini system leaves out several things that real Vue handles:

  • Batching. Vue does not run effects immediately inside trigger. It schedules them in a queue so a component renders once per tick even if you change ten values. See DOM Update Timing and nextTick.
  • Laziness. A computed is an effect that is only re-evaluated when read after a change.
  • Deep reactivity on demand. Nested objects are wrapped in proxies lazily, when you first read them through the parent.
  • Arrays, Maps and Sets. These need special handling so that push, length and size track correctly.
  • Refs. A ref is the same idea on an object with a value getter and setter.

Vue 3.5 rewrote much of the internals for lower memory use and speed, but the model you just built, subscribe on read and notify on write, is unchanged.

Opting out of deep tracking

Deep reactivity is convenient, and expensive when the data is big. A proxy is created for each nested object you touch, and every read is tracked. Three tools let you reduce that cost or avoid tracking altogether.

  • shallowRef(value) tracks only .value itself. Assigning a new value triggers updates; mutating something inside the value does not.
  • triggerRef(ref) manually tells subscribers of a shallow ref that it changed, after you mutated its contents in place.
  • markRaw(object) flags an object so Vue never turns it into a proxy, even when it sits inside reactive state. Use it for class instances, third-party objects (a chart, a map, an editor) and large read-only data.
shallowRef, triggerRef and markRaw

Press Push item twice: the screen still says 3 items, because the shallow ref only watches .value, not what is inside. Check memory reports 5, so the data really changed. triggerRef makes the screen catch up, and Replace the object triggers an update the ordinary way. In the second half, the plain object is a reactive proxy and the markRaw object is not.

Use these tools for measured problems, not by default. Replacing data (list.value = newList) with a shallow ref is a good fit for large arrays you receive from an API and never edit in place. The lesson on large lists and lazy loading returns to this idea.

If you ever need the original object behind a proxy, toRaw(proxy) gives it back. Mutating the raw object will not trigger updates, which is occasionally useful for hot loops and usually a bug.

Custom refs with customRef

ref, shallowRef and computed cover most needs. When you want a ref whose reads and writes run your own code, Vue gives you customRef. You pass it a factory that receives two functions, track and trigger, and returns an object with a get and a set:

  • call track() inside get to say "whoever is reading this value depends on it";
  • call trigger() inside set (or any time later) to say "dependents must re-run now".

You decide when trigger() happens. That is the whole trick: a debounced ref stores the new value immediately but delays the notification, so watchers and the template see the change only after the user pauses typing.

JavaScript
import { customRef } from "vue";

function useDebouncedRef(initial, delay = 300) {
  let value = initial;
  let timer;
  return customRef((track, trigger) => ({
    get() {
      track();
      return value;
    },
    set(next) {
      clearTimeout(timer);
      timer = setTimeout(() => {
        value = next;
        trigger();
      }, delay);
    },
  }));
}
A debounced ref built with customRef

Type a word fast: the immediate value follows every key, while the debounced one and the counter change once, after you stop. Note the design choice: the template can still bind v-model="settled" directly, because a custom ref is a normal ref from the outside (.value, auto-unwrapping, watch, toRef).

Two cautions. Do not call trigger() inside get, or you create an infinite loop. And a custom ref is a hand-made contract, so test it; watch(typed, ...) plus a timer is often simpler when you only need the delayed effect (see composable patterns for a useDebounce built that way).

Storage-backed refs and VueUse

Another classic custom ref reads from and writes to storage: get returns the in-memory value, set also saves it. You rarely write that by hand, because VueUse, a large community library of composables, ships tested versions. These snippets are read-only, since the runner cannot install packages:

JavaScript
import { useStorage, refDebounced, useThrottleFn, useMouse } from "@vueuse/core";

const theme = useStorage("theme", "light");     // a ref kept in localStorage
const query = ref("");
const debouncedQuery = refDebounced(query, 300); // like our customRef, tested
const save = useThrottleFn(saveDraft, 1000);     // at most one call per second
const { x, y } = useMouse();                     // refs updated on mousemove

Each VueUse composable also cleans up after itself when the component unmounts. That brings us to effectScope, the tool that makes such cleanup possible outside components. It creates a bucket that collects every watcher, computed and effect created inside scope.run(() => ...). Calling scope.stop() disposes of all of them at once, which is how a composable can be started and stopped from plain JavaScript. Inside components you never need it, because the component is the scope; see onScopeDispose in composable patterns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the get trap of a reactive proxy do for reactivity?

    Every read goes through the get trap, which calls track. That is how the active effect becomes subscribed to exactly the properties it read.
  2. 2. Why does ref() need a .value property while reactive() does not?

    Proxies work on objects. A number or string cannot be proxied, so a ref wraps it in an object whose value accessors do the tracking and triggering.
  3. 3. In the mini system, why did changing tax not re-run the effect while showTax was false?

    Dependencies are collected from what the effect reads. The if branch skipped tax, so no subscription existed until showTax became true.
  4. 4. You mutate list.value.items.push(4) on a shallowRef. How do you make the screen update without replacing the object?

    A shallow ref only reacts to changes of .value. After mutating inside it, triggerRef notifies the subscribers manually.

Summary

  • Reactivity needs to know who read a value and when it was written; Vue intercepts reads and writes with proxies.
  • track subscribes the running effect on a read; trigger re-runs subscribed effects on a write.
  • Dependencies live in a WeakMap of Maps of Sets, one set of effects per object property, and are re-collected on every run.
  • ref uses getter and setter on .value because primitives cannot be proxied.
  • Real Vue adds batching, lazy computeds, lazy deep proxies and collection handling on top of the same model.
  • shallowRef, triggerRef and markRaw reduce tracking cost for large data and non-plain objects.

Next, see how these updates reach the DOM in DOM Update Timing and nextTick.