effect and Dependency Tracking: Implementing track and trigger

Understand the role of effect in Vue 3 reactivity and implement dependency tracking with track and update notification with trigger.

🎯 Introduction

Previously, we implemented the get and set traps in reactive, allowing Vue to intercept reads and writes. We left two placeholders: track in get to track dependencies, and trigger in set to trigger updates. What do these functions record, and what do they update? This article fills in those gaps.

Here are a few terms we will explain along the way:

  • Dependency: the relationship between data and the code that uses it.
  • Dependency tracking: recording which effects use that data.
  • Triggering updates: notifying those effects to run again when data changes.

By the end, you will be able to:

  • Explain what effect does.
  • Describe where dependency records are stored and how they are organized.
  • Implement simplified versions of track and trigger.
  • Connect reactive and effect into a complete reactive update flow.

The excerpts use Vue 3.5.x from the GitHub vuejs/core repository, primarily packages/reactivity/src/effect.ts. Run the examples with Node.js v22.


🧱 What Is effect?

How does Vue know what to update when data changes? It records consumers rather than guessing. When code reads reactive data, Vue records the effect responsible. When the data changes, it notifies the recorded effects.

effect wraps a function. It executes the function immediately, recording the reactive values read during that execution, so changes to those values can rerun the function:

const obj = reactive({ name: 'noxussj' });

effect(() => {
    // Runs immediately once
    // Then reruns automatically whenever obj.name changes
    console.log('name:', obj.name);
});

Think of subscribing to a newspaper: you register once (the initial execution records your subscription), and future editions (data changes) are delivered automatically (the function reruns).

How does Vue know which effect is running while the function reads data? In this simplified implementation, a global activeEffect variable holds that information. Before running the function, the effect assigns itself to activeEffect, then clears it afterward. Any reactive read during execution can identify its consumer through this variable:

// Simplified from packages/reactivity/src/effect.ts

// The effect currently executing
let activeEffect = null;

function effect(fn) {
    // Wrap the function in an effect object with a run method
    const _effect = {
        fn,
        run() {
            try {
                // Make this effect active before execution
                activeEffect = _effect;
                return fn(); // Run the user's function
            } finally {
                // Clear it whether execution succeeds or throws
                activeEffect = null;
            }
        },
    };

    _effect.run(); // Run immediately and collect initial dependencies
    return _effect;
}

The three steps in run—activate, execute, clear—control dependency tracking: reads are tracked only while activeEffect has a value.


🧱 targetMap: Where the Records Live

Where does Vue store these records?

Vue 3 uses a global container called targetMap to record which effects use which properties of which objects. This teaching model organizes the records into three levels:

// Simplified from packages/reactivity/src/dep.ts
const targetMap = new WeakMap();

// Three levels, from outermost to innermost:
// 1. Object, such as obj
// 2. Property key, such as 'name' or 'age'
// 3. Effects that read that property

Suppose obj = reactive({ name: 'noxussj', age: 18 }), effect1 reads both properties, and effect2 reads only name. The records look like this:

targetMap
└── obj (level 1: indexed by object)
    ├── 'name' → effect1, effect2 (level 2: property key; level 3: effect set)
    └── 'age'  → effect1

When obj.name changes, Vue can find effect1 and effect2. Each container serves a purpose:

  • WeakMap at level 1 holds its keys weakly, so it does not prevent garbage collection—the JavaScript mechanism that frees unused memory. Once an object is no longer reachable, its dependency records can be collected with it.
  • Map at level 2 groups records by property key. Changing obj.name notifies effects that read name, without unnecessarily rerunning effects that only read age.
  • Set at level 3 removes duplicates automatically. Reading obj.name twice in one effect registers that effect only once, avoiding duplicate notifications.
Compare this with Vue 2: each property has a Dep instance containing Watchers. This simplified Vue 3 model uses a global targetMap lookup instead. The purpose is the same; the storage differs. See the Vue 2 source code course for that implementation.

🧱 track: Recording Consumers

When are these records created? When reactive data is read, through the track call in the get trap from the previous article.

track adds the currently executing effect, activeEffect, to the Set associated with the target object and property. It walks through the three levels, creating missing containers:

// Simplified from packages/reactivity/src/dep.ts
function track(target, key) {
    // No active effect means this read does not need tracking
    if (!activeEffect) return;

    // Level 1: find or create the object's Map
    let depsMap = targetMap.get(target);
    if (!depsMap) {
        depsMap = new Map();
        targetMap.set(target, depsMap);
    }

    // Level 2: find or create the property's Set
    let dep = depsMap.get(key);
    if (!dep) {
        dep = new Set();
        depsMap.set(key, dep);
    }

    // Level 3: register the current effect without duplicates
    dep.add(activeEffect);
}

Its task is simple: record the effect that reads this property while running. The initial if (!activeEffect) return matters: a read outside an effect, such as logging obj.name directly, has no subscriber to register. Skipping it avoids unnecessary records.


🧱 trigger: Notifying Effects

Once consumers are registered, how are they notified after a write? The set trap calls trigger.

trigger performs the reverse lookup: find the Set for this object and property, then rerun each effect in it:

// Simplified from packages/reactivity/src/dep.ts
function trigger(target, key) {
    // Level 1: no Map means no dependencies for this object
    const depsMap = targetMap.get(target);
    if (!depsMap) return;

    // Level 2: find the property's Set
    const dep = depsMap.get(key);
    if (!dep) return;

    // Level 3: iterate a copy and rerun each effect
    new Set(dep).forEach((effect) => {
        effect.run();
    });
}

Notice the new Set(dep) copy before iteration. Rerunning an effect reads reactive data again, invoking track and potentially modifying the same Set. In implementations that remove and re-add subscriptions, mutating the Set being traversed can cause repeated visits or an infinite loop. Iterating a copy avoids that risk.

Tracking again during execution is also essential: each run can collect its dependencies anew, allowing records to reflect the values used by the latest execution.


🧱 Connecting the Complete Flow

We have covered the consumers, storage, registration, and notification. Combine them with reactive to build a runnable mini reactivity system:

demo.js
// ===== reactive from the previous article: intercept reads and writes =====
function reactive(target) {
    return new Proxy(target, {
        get(target, key, receiver) {
            const result = Reflect.get(target, key, receiver);
            track(target, key); // Track dependencies on reads
            return result;
        },
        set(target, key, value, receiver) {
            const result = Reflect.set(target, key, value, receiver);
            trigger(target, key); // Trigger updates on writes
            return result;
        },
    });
}

// ===== effect / track / trigger from this article =====
const targetMap = new WeakMap(); // All dependency records
let activeEffect = null; // The currently executing effect

function effect(fn) {
    const _effect = {
        fn,
        run() {
            try {
                activeEffect = _effect; // Activate this effect
                return fn();
            } finally {
                activeEffect = null; // Clear it afterward
            }
        },
    };
    _effect.run(); // Run immediately
    return _effect;
}

function track(target, key) {
    if (!activeEffect) return; // Track only while an effect is running
    let depsMap = targetMap.get(target);
    if (!depsMap) {
        depsMap = new Map();
        targetMap.set(target, depsMap);
    }
    let dep = depsMap.get(key);
    if (!dep) {
        dep = new Set();
        depsMap.set(key, dep);
    }
    dep.add(activeEffect); // Register the current effect
}

function trigger(target, key) {
    const depsMap = targetMap.get(target);
    if (!depsMap) return;
    const dep = depsMap.get(key);
    if (!dep) return;
    new Set(dep).forEach((effect) => {
        effect.run(); // Rerun each effect
    });
}

// ===== Usage =====
const obj = reactive({ name: 'noxussj' });

effect(() => {
    console.log('name:', obj.name);
});
// Logs: name: noxussj (the immediate initial run)

obj.name = 'Ming';
// Logs: name: Ming (trigger reruns the effect automatically)

Save this as demo.js and run node demo.js with Node.js v22. Changing obj.name automatically reruns the function. The complete cycle is: effect runs → reads obj.name → get intercepts → track registers the effect → obj.name changes → set intercepts → trigger reruns recorded effects → reads during the rerun collect dependencies again. Each later change repeats the cycle.

Component rendering, computed values, and watchEffect all participate in this reactive-effect model. Conceptually, watchEffect(() => { ... }) from the Vue 3 course hands your function to the reactivity system to manage its execution.

⚠️ Nested Effects and Cleanup (Overview)

The simplified implementation omits two real-world cases. For now, understand why they matter; you do not need to implement them yet.

Nested effects. An effect may create another effect. The inner execution overwrites activeEffect; clearing it afterward loses the outer effect, so subsequent reads are not tracked correctly. The full implementation preserves the previous active effect for each nested execution and restores it afterward, behaving like a stack.

Cleanup when branches change. Consider:

effect(() => {
    // Read name only when show is true
    console.log(obj.show ? obj.name : 'hidden');
});

When obj.show changes from true to false, the rerun no longer reads obj.name. Later changes to name should therefore stop notifying this effect. The full implementation refreshes subscriptions across runs, removing dependencies that were not used again so they match the active branch.


❓ Questions and Answers

Q1: Why use WeakMap rather than Map for the outer level?

Its keys are the target objects. WeakMap does not keep them alive merely because dependency records exist. Unreachable objects and their associated records can be collected. A regular Map would retain those objects until their entries were removed, potentially leaking memory.

Q2: Why use Set rather than an array for effects?

To avoid duplicates. An effect may read the same property several times. An array could register it repeatedly and rerun it multiple times per change; a Set records it once.

Q3: How does Vue 3's effect relate to Vue 2's Watcher?

They play similar roles: effect roughly corresponds to Watcher, and the dependency Set in this teaching model roughly corresponds to Dep. Vue 2 stores subscriptions per property; Vue 3 uses a global lookup. Both notify consumers when data changes.

Q4: Are reads in ordinary functions tracked?

Only if they occur while an effect is running. track first checks activeEffect; an ordinary read outside that execution is simply a property access.

Q5: Why collect dependencies again on every run?

Dependencies can change. In obj.show ? obj.name : 'hidden', different branches read different properties. Refreshing subscriptions and removing stale ones keeps notifications aligned with the data currently used.


🧪 Exercise

Complete these three functions without looking up the implementation. Changing obj.name should rerun the effect automatically. Save it as a .js file and run it with Node.js v22:

const targetMap = new WeakMap();
let activeEffect = null;

function effect(fn) {
    // Your code here (hint: run fn immediately with activeEffect pointing to this effect)
}

function track(target, key) {
    // Your code here (hint: find or create the object Map and property Set, then add activeEffect)
}

function trigger(target, key) {
    // Your code here (hint: copy the property's Set, then call effect.run for each entry)
}

function reactive(target) {
    return new Proxy(target, {
        get(target, key, receiver) {
            const result = Reflect.get(target, key, receiver);
            track(target, key);
            return result;
        },
        set(target, key, value, receiver) {
            const result = Reflect.set(target, key, value, receiver);
            trigger(target, key);
            return result;
        },
    });
}

const obj = reactive({ name: 'noxussj', age: 18 });

effect(() => {
    console.log('name:', obj.name);
});

// Expected output:
// name: noxussj
// name: Ming
obj.name = 'Ming';

// Changing age should not rerun the effect: tracking is property-specific
obj.age = 20;

For an extra challenge, read both obj.name and obj.age in the effect and verify that changing either reruns it. How are these two subscriptions stored in targetMap?


🎉 You now understand effects and dependency tracking! Next, we will explore ref and computed: how Vue makes primitives reactive without proxying them directly, and how computed values cache their results.