Senior LevelVue JS
How does Vue 3 reactivity work internally with ES6 Proxies and track/trigger mechanics?
❓ Interview Prompt: Explain Vue 3 reactivity engine: ES6 Proxies, WeakMap target storage, activeEffect tracking during render, and trigger notifications.
Vue 3 reactivity is powered by ES6 Proxies and a reactive effect tracking engine:
The Reactivity Pipeline:
1
Proxy Interception: When wrapping an object in 'reactive()' or 'ref()', Vue creates a Proxy that intercepts property reading ('get' trap) and property writing ('set' trap).
2
Dependency Tracking ('track()'): When a component renders or a computed/watch effect runs, Vue sets a global variable 'activeEffect' to the currently running function. When the Proxy's 'get' trap is triggered, Vue calls 'track(target, key)', storing a reference in a global WeakMap structure: 'WeakMap<TargetObject, Map<PropertyKey, Set<ReactiveEffect>>>'.
3
Change Notification ('trigger()'): When a property is modified, the Proxy's 'set' trap intercepts the assignment and calls 'trigger(target, key)'. Vue looks up the 'Set' of effects associated with that property in the WeakMap and schedules them to re-run asynchronously in the microtask queue.
Why WeakMap?
Using a 'WeakMap' ensures that if a reactive target object is removed from the DOM, it is automatically garbage collected without memory leaks.
Code Implementation Example
javascript
// Conceptual representation of Vue 3 Reactivity Engine
const targetMap = new WeakMap(); // Stores all reactive targets
let activeEffect = null;
function track(target, key) {
if (!activeEffect) return;
let depsMap = targetMap.get(target);
if (!depsMap) targetMap.set(target, (depsMap = new Map()));
let dep = depsMap.get(key);
if (!dep) depsMap.set(key, (dep = new Set()));
dep.add(activeEffect); // Record dependency!
}
function trigger(target, key) {
const depsMap = targetMap.get(target);
if (!depsMap) return;
const dep = depsMap.get(key);
if (dep) dep.forEach(effect => effect()); // Re-run subscribed effects!
}💡Internal Proxy get/set interception with WeakMap track and trigger mechanics.
🎯 Interview Key Takeaway
Vue 3 uses ES6 Proxies to intercept get/set operations, storing dependency subscribers in a WeakMap for automatic garbage collection.
#Vue 3#Reactivity#Proxies#Senior
Back to all Vue JS Questions→