Full answer
The idea is automatic dependency tracking. An effect is a function that reads state. While it runs, every state read should register that effect as a subscriber of that exact property. When the property changes, only its subscribers run again.
Pieces:
- Storage: a
WeakMapfrom each raw target object to aMapfrom key to aSetof effects. A WeakMap lets the garbage collector remove the data when the target is no longer used. activeEffect: a variable set while an effect runs, so thegettrap knows who is reading.gettrap: calltrack(target, key)to add the active effect, then return the value withReflect.get. If the value is an object, return a reactive proxy for it, created lazily and cached, so nested state is reactive without wrapping everything up front.settrap: set the value withReflect.set(which respects the receiver and setters), compare the old and new value withObject.is, and calltrigger(target, key)when they differ.effect(fn): runsfnonce immediately withactiveEffectset, so its reads are tracked. Run effects in a copy of the set, because running one may add or remove subscribers while you iterate.- Arrays:
pushwrites the new index, and the array length then updates by itself, so the following write tolengthsees an unchanged value and would not trigger anything. When a new index is added to an array, trigger thelengthsubscribers too.
Guard against loops: an effect that writes to state it also reads would trigger itself forever, so skip the effect that is currently running.
What this simple version leaves out: cleaning up dependencies before each re-run (so branches that are no longer taken stop subscribing), batching updates and running them asynchronously, has and ownKeys traps so in and Object.keys are reactive, deleteProperty, and computed values with caching. Vue 3 does all of these. The key point for an interview is the structure: track in get, trigger in set, and a registry keyed by target and property.
const targetMap = new WeakMap();
const proxyCache = new WeakMap();
let activeEffect = null;
function track(target, key) {
if (!activeEffect) return;
let keyMap = targetMap.get(target);
if (!keyMap) targetMap.set(target, (keyMap = new Map()));
let subscribers = keyMap.get(key);
if (!subscribers) keyMap.set(key, (subscribers = new Set()));
subscribers.add(activeEffect);
}
function trigger(target, key) {
const subscribers = targetMap.get(target)?.get(key);
if (!subscribers) return;
for (const run of [...subscribers]) {
if (run !== activeEffect) run(); // skip the effect that is running, to avoid self-loops
}
}
function effect(fn) {
const run = () => {
const previous = activeEffect;
activeEffect = run;
try {
return fn();
} finally {
activeEffect = previous;
}
};
run();
return run;
}
function reactive(raw) {
if (proxyCache.has(raw)) return proxyCache.get(raw);
const proxy = new Proxy(raw, {
get(target, key, receiver) {
track(target, key);
const value = Reflect.get(target, key, receiver);
return typeof value === 'object' && value !== null ? reactive(value) : value;
},
set(target, key, value, receiver) {
const hadKey = Object.hasOwn(target, key);
const oldValue = target[key];
const result = Reflect.set(target, key, value, receiver);
if (!hadKey || !Object.is(oldValue, value)) {
trigger(target, key);
if (Array.isArray(target) && !hadKey) trigger(target, 'length');
}
return result;
},
});
proxyCache.set(raw, proxy);
return proxy;
}
const rawUser = { name: 'Asha' };
const state = reactive({ count: 0, user: rawUser, items: [1, 2, 3] });
effect(() => console.log('count effect:', state.count));
effect(() => console.log('name effect:', state.user.name));
effect(() => console.log('items effect: length', state.items.length));
console.log('--- change count');
state.count++;
console.log('--- same value, no re-run');
state.count = 1;
console.log('--- change nested name');
state.user.name = 'Ben';
console.log('--- push to array');
state.items.push(4);
console.log('--- unrelated key does not trigger');
state.other = 'x';
console.log('--- same raw object gives the same proxy:', reactive(rawUser) === state.user);
let runs = 0;
effect(() => {
runs++;
state.count = state.count + 1; // writes what it reads; must not loop forever
});
console.log('self-writing effect ran', runs, 'time(s), count is', state.count);Run with Node.js v24.22.1 as js-100.js; two runs gave identical output. Output: count effect: 0 name effect: Asha items effect: length 3 --- change count count effect: 1 --- same value, no re-run --- change nested name name effect: Ben --- push to array items effect: length 4 --- unrelated key does not trigger --- same raw object gives the same proxy: true count effect: 2 self-writing effect ran 1 time(s), count is 2
Key points
- Track in the get trap: add the active effect to a WeakMap, then Map, then Set registry.
- Trigger in the set trap after Reflect.set, and only when Object.is says the value changed.
- Wrap nested objects lazily on read, with a cache so the same object gives the same proxy.
- Arrays need extra care: adding an index changes length without a length write.
- Missing in a small version: dependency cleanup, batching, has/ownKeys/delete traps, computed values.
Common mistakes
- Writing to the raw object and expecting effects to run.
- Skipping Reflect and breaking setters, inheritance, or receiver behavior.
- Iterating the live subscriber Set while effects change it.
- Not guarding against an effect that writes to its own dependency.
Follow-ups
- How does Vue 3 clean up dependencies so effects stop reacting to branches that are no longer used?
- How would you batch several updates and run each effect once, asynchronously?
- What are the trade-offs between Proxy-based reactivity and getter and setter based reactivity as in Vue 2?
Tips
- Draw the registry: WeakMap of target to Map of key to Set of effects.
- Say track in get, trigger in set, and why Reflect is used.
- List what is missing and name Vue 3 and MobX as production solutions.