javascript / expert
Snippet
Proxy Mutation Trap for Immutability Testing in React Hooks
This snippet creates a recursive JavaScript Proxy wrapper designed for test suites. It intercepts state mutation attempts in React hook return values at runtime, guaranteeing strict object immutability by invoking an error handler whenever property setter traps are triggered.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function createImmutableProxy(target, onError) {return new Proxy(target, {get(obj, prop) {const val = Reflect.get(obj, prop);if (val && typeof val === 'object') {return createImmutableProxy(val, onError);}return val;},set(obj, prop, value) {onError(new TypeError(`Direct mutation forbidden on property: ${String(prop)}`));return false;}});}
react
Breakdown
1
return new Proxy(target, {
Instantiates a trap-based dynamic Proxy surrounding the target state object.
2
if (val && typeof val === 'object') {
Recursively proxies nested objects to enforce deep immutability checking.
3
set(obj, prop, value) {
Intercepts property write access and prevents state mutation.
4
onError(new TypeError(...));
Dispatches a runtime error callback whenever state immutability is violated.