Dependency Tracking and Update Notification: Dep and Watcher
🎯 Introduction
The previous article used defineReactive to intercept property reads and writes with get and set. We can detect a change—but how does Vue identify which parts of the view need updating?
By the end of this article, you will be able to answer that question. Dep manages who uses a piece of data, while Watcher represents work that needs to run when it changes. Their collaboration connects dependency tracking to update notification.
🪤 Who Should Be Notified?
Recall the setter from the previous article:
set(newVal) {
if (newVal === val) return;
val = newVal;
// Trigger an update... but whose update?
}
One property can be used in multiple places. For example, both a header component and a sidebar may display data.name. Both must update when name changes, while components that never read it should remain unaffected.
Each property therefore needs a subscription list: register its users, then notify them when it changes. Dep manages that list, and each subscriber is a Watcher.
💡 An Analogy: Publishers and Subscribers
A newspaper subscription provides a useful analogy:
- Dep is the publisher's subscriber list: each publisher (property) keeps track of its subscribers.
- Watcher is a reader: each reader (component or computed property) may subscribe to several publications.
- When a new issue appears: the publisher delivers it to subscribers on the list, rather than contacting everyone.
Subscription is automatic: reading a publication (accessing a property) registers the reader. This is dependency tracking. Readers also remember their publishers so they can unsubscribe later: Watcher records its Deps.
🧱 Dep: A Property's Subscriber List
Dep is defined in src/core/observer/dep.js. Its core structure is small; this version simplifies the Vue 2.7.16 source by omitting edge cases:
// Simplified from src/core/observer/dep.js
let uid = 0;
export default class Dep {
constructor() {
this.id = uid++;
this.subs = []; // Subscribers (an array of Watchers)
}
addSub(sub) {
this.subs.push(sub);
}
depend() {
if (Dep.target) {
Dep.target.addDep(this);
}
}
notify() {
const subs = this.subs.slice();
for (let i = 0; i < subs.length; i++) {
subs[i].update();
}
}
}
Dep.target = null; // The Watcher currently being evaluated
Here is what each member does:
- subs: stores the Watchers that depend on this property.
- addSub: adds a Watcher to the list.
- depend: starts dependency tracking. Instead of calling
addSubdirectly, it callsDep.target.addDep(this)so the Watcher handles registration. The next section explains why. - notify: iterates through subscribers and calls each Watcher's
update()when data changes.
Dep.target is a shared static property pointing to the Watcher currently being evaluated. Only one Watcher is the active evaluation target at a time, so a global pointer connects property access to the correct Watcher.
🧱 Watcher: Work That Depends on Data
Watcher is defined in src/core/observer/watcher.js. Component rendering, computed properties, and user-defined watchers all use it. Here is the simplified core:
// Simplified from src/core/observer/watcher.js
export default class Watcher {
constructor(vm, expOrFn) {
this.vm = vm;
this.deps = []; // Deps this Watcher subscribes to
this.getter = expOrFn; // Evaluation function, such as rendering
this.value = this.get();
}
get() {
pushTarget(this); // Set Dep.target to the current Watcher
const value = this.getter.call(this.vm, this.vm);
popTarget(); // Restore Dep.target after evaluation
return value;
}
addDep(dep) {
if (!this.deps.includes(dep)) {
this.deps.push(dep);
dep.addSub(this); // Register this Watcher with the Dep too
}
}
update() {
this.run();
}
run() {
this.value = this.get(); // Re-evaluate, triggering rendering again
}
}
The three steps inside get() are crucial:
pushTarget(this): set the globalDep.targetto this Watcher, identifying the current evaluation.- Execute the getter: for example, render the component. Reading properties such as
data.nameinvokes their getters. popTarget(): restore the previous target when evaluation finishes.
addDep records the subscription on both sides: the Watcher remembers the Dep, and the Dep adds the Watcher to its list. Registration is bidirectional, supporting deduplication and cleanup when the component is destroyed.
⚡ Dependency Tracking: Register During Evaluation
Now combine Dep and Watcher with the previous article's defineReactive. Its getter contains this key call:
// Simplified from defineReactive in src/core/observer/index.js
Object.defineProperty(obj, key, {
get() {
if (Dep.target) {
dep.depend(); // Register the Watcher currently being evaluated
}
return val;
},
set(newVal) {
if (newVal === val) return;
val = newVal;
dep.notify(); // Notify all subscribers when the value changes
},
});
A complete dependency tracking cycle works as follows:
- Create the render Watcher: during mounting, Vue creates a Watcher whose getter performs rendering.
- Begin evaluation:
get()setsDep.targetto that Watcher. - Read data: rendering accesses
data.name, invoking its getter. - Register: the getter sees
Dep.targetand callsdep.depend(). The property's Dep records the Watcher, and the Watcher records the Dep. - Finish evaluation:
popTarget()restores the previous target. Each accessed property has registered its dependency.
No manual dependency declarations are required. Properties used by the template are automatically tracked during evaluation. That is dependency tracking.
⚡ Update Notification: Notify Subscribers
Once subscriptions exist, updates follow naturally. Consider:
this.name = 'new name';
The sequence is:
- Invoke
set: the setter detects a changed value. - Call
dep.notify(): the property's Dep retrieves its subscribers. - Call each
update(): every subscribed Watcher receives the notification. In this article's simplified version, it callsrun()directly, evaluating again and re-rendering.
Components that never used the property are absent from the list and receive no notification. This is how Vue targets the relevant updates.
⚖️ A Many-to-Many Relationship
Dep and Watcher have a many-to-many relationship:
- One Watcher depends on several properties: a render function using
nameandagesubscribes to both Deps. - One property has several Watchers: if both the header and sidebar use
name, its Dep has multiple subscribers.
Both sides therefore keep records: Dep stores subs, and Watcher stores deps. When a component is destroyed, its Watcher can use deps to remove itself from each Dep's subs, preventing unnecessary notifications.
❓ Knowledge Check
Q1: Why does depend call Dep.target.addDep(this) instead of dep.addSub(Dep.target) directly?
The Watcher needs to remember its subscriptions too. Handling registration through Watcher maintains its deps list and supports deduplication. Cleanup when the component is destroyed also relies on this list.
Q2: Why use a static Dep.target instead of passing a parameter?
Evaluation calls application code, which may access properties through many nested calls. A global pointer makes the current Watcher available to getters at any depth without passing it through every function. Only one target is active at a time.
Q3: Is a property tracked even if it never changes?
Yes. Tracking depends on reads, not writes. Accessing a property during rendering registers the dependency. Registration is inexpensive and ensures that any later change can notify the right subscribers.
Q4: Does the page update immediately after this.name = 'x'?
No. Vue queues Watchers asynchronously and flushes them after synchronous code finishes. Reading the DOM immediately after changing data still returns the old content, which is why this.$nextTick exists. This article's implementation is synchronous to make the main sequence easier to follow.
🧪 Exercise
Extend the previous article's defineReactive with small Dep and Watcher implementations so changing data automatically reruns a callback. Use Node.js v22; the reference source is vue@2.7.16. Run the file with node filename.js.
// Simplified defineReactive from the previous article
function defineReactive(obj, key, val) {
const dep = new Dep();
Object.defineProperty(obj, key, {
get() {
if (Dep.target) {
dep.depend();
}
return val;
},
set(newVal) {
if (newVal === val) return;
val = newVal;
dep.notify();
},
});
}
class Dep {
// Write your code here: subs array, addSub, depend, and notify
}
class Watcher {
// Write your code here: call get() during construction; set Dep.target before executing the callback
}
// Verify: the callback should log twice, with the new value on the second call
const data = {};
defineReactive(data, 'name', 'Alex');
new Watcher(() => console.log('name changed to:', data.name));
data.name = 'Sam';
Hint: Dep and Watcher each need about 15 lines, plus Dep.target = null. When you run the result, the second message should be name changed to: Sam.
🎉 You now understand how Dep and Watcher work together! Interception detects changes, Dep manages subscribers, and Watcher performs updates. Next, we will see how Vue batches multiple changes into one render with an asynchronous queue.
