JavaScript & V8 Internals (536 Qs)•Part 8: Modern JavaScript APIs, WeakRef, Proxy & Performance (464 - 536)
What are the real world use cases of proxy?
junior LevelCode ExampleFormsPerformanceHTTP & REST APIs
Proxies are not used in regular day to day JavaScript work but they enabled many exciting programming patterns. Some of the real world use cases are listed below,
- Vue3 used proxy concept to implement reactive state
- SolidJS implemented reactive stores
- Immerjs built upon proxy to track updates to immutable updates
- ZenStack improved Prisma ORM for access control layer
Practical Code Example
javascript
// Real-world Use Cases for Proxy:
// 1. Schema validation on objects:
const validator = {
set(target, prop, value) {
if (prop === 'age' && (typeof value !== 'number' || value < 0)) {
throw new TypeError('Invalid age');
}
target[prop] = value;
return true;
}
};
const user = new Proxy({}, validator);
user.age = 25; // Success
// user.age = -5; // Throws TypeError!