javascript / expert
Snippet
Transparent Reactive State via Recursive Proxies
Using the Proxy API recursively allows for the creation of deeply observable objects. Unlike Object.defineProperty, Proxies intercept operations directly, enabling features like transparent reactivity, validation, or logging for nested structures without manual instrumentation of every property.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const observer = (target, handler) => {return new Proxy(target, {get(obj, prop) {const val = obj[prop];return (typeof val === 'object' && val !== null) ? observer(val, handler) : val;},set(obj, prop, value) {const success = Reflect.set(obj, prop, value);if (success) handler(prop, value);return success;}});};const state = observer({ user: { name: 'Jonas' } }, (p, v) => console.log(`${p} changed to ${v}`));state.user.name = 'Markus'; // Triggers handler
nextjs
Breakdown
1
return new Proxy(target, { ... });
Wraps the target object in a Proxy to intercept operations like 'get' and 'set'.
2
return (typeof val === 'object' && val !== null) ? observer(val, handler) : val;
Recursively wraps nested objects in Proxies when they are accessed, enabling deep tracking.
3
const success = Reflect.set(obj, prop, value);
Uses Reflect to safely perform the default assignment operation on the target object.