javascript / expert
Snippet
Proxy-Based Deep State Mutability Tracking for Custom React Dispatchers
This advanced snippet uses JavaScript Proxy traps and Reflect API within a custom React hook to intercept object reads and mutations. It creates a controlled draft environment allowing nested structural mutations to be recorded safely before committing immutable state updates.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import { useState, useCallback } from 'react';function createDraftProxy(target, changes) {return new Proxy(target, {get(obj, prop) {const val = Reflect.get(obj, prop);if (typeof val === 'object' && val !== null) {return createDraftProxy(val, (changes[prop] = changes[prop] || {}));}return val;},set(obj, prop, value) {if (Reflect.get(obj, prop) !== value) {changes[prop] = value;return Reflect.set(obj, prop, value);}return true;}});}export function useDraftState(initialState) {const [state, setState] = useState(initialState);const updateState = useCallback((recipe) => {setState((prev) => {const draft = JSON.parse(JSON.stringify(prev));const changes = {};const proxy = createDraftProxy(draft, changes);recipe(proxy);return draft;});}, []);return [state, updateState];}
react
Breakdown
1
return new Proxy(target, { ... });
Wraps target state objects with a Proxy handler to intercept set and get operations dynamically.
2
const val = Reflect.get(obj, prop);
Uses Reflect.get to cleanly read target properties while preserving correct target binding.
3
set(obj, prop, value) { ... Reflect.set(obj, prop, value); }
Intercepts mutation attempts, tracks modified keys into a change dictionary, and writes updates via Reflect.set.
4
recipe(proxy);
Passes the Proxy draft instance to user-supplied mutative callback functions safely.