Learn the concept
Proxy & Reflect
A Proxy wraps an object and intercepts fundamental operations (get, set, delete, etc.) through handler traps. They enable metaprogramming patterns like validation, logging, lazy loading, and implementing reactive systems.
Proxy Basics:
new Proxy(target, handler) creates a proxytarget: The original object to wraphandler: Object with trap methodsCommon Traps:
get(target, prop, receiver): Property accessset(target, prop, value, receiver): Property assignmenthas(target, prop): 'in' operatordeleteProperty(target, prop): delete operatorapply(target, thisArg, args): Function callsconstruct(target, args): new operatorUse Cases:
const validator = {
set(target, prop, value) {
if (prop === 'age') {
if (!Number.isInteger(value)) {
throw new TypeError('Age must be an integer');
}
if (value < 0 || value > 150) {
throw new RangeError('Age must be between 0 and 150');
}
}
target[prop] = value;
return true;
}
};
const person = new Proxy({}, validator);
person.name = 'Alice'; // OK
person.age = 30; // OK
person.age = -5; // RangeError
person.age = 'thirty'; // TypeErrorWrapping state objects in Proxies that track property access and trigger UI updates on mutation, as used by Vue 3 and MobX
Creating validation proxy wrappers that enforce data shapes, required fields, and type coercion before data reaches business logic
Using Proxies to enable mutable-style code that produces immutable results with structural sharing, as implemented by Immer
Build a lightweight reactive store supporting property change subscriptions, computed properties, batched updates, and deep reactivity
Create a model system using Proxy where schemas automatically validate assignments, provide defaults, and log access patterns
Vue 3 reactivity is built entirely on Proxies for automatic dependency tracking, deep reactivity, and property addition detection
Uses Proxy for draft states enabling mutable-looking code that produces immutable updates with structural sharing