...

/

Handling State Proxies Using the useProxy Hook

Handling State Proxies Using the useProxy Hook

Learn about the useProxy custom hook that leverages ES6 Proxy to enable direct assignments, simplifying state updates without needing dispatch functions.

Introduction to the useProxy hook

In the internal implementation of the useProxy custom hook, the React useState, useRef, and useEffect hooks are utilized.

The thinking behind either fixing or improving the React state never ends. One cool idea originates from the question, "Why can't we just do a plain assignment for states instead of using the dispatch approach?" One of the technical issues blocking us is that the assignment can't be done unless there's an object or something to hold the state. So, if we were to allow the storing of properties under an object like so:

const p = useProxy({ count: 0, text: '' })

Then we could turn a dispatch into an assignment like the following:

p.count++
p.text = 'Hello World'

Implementing the useProxy Hook

Let's take a look at how we can design such things with the help of the Proxy introduced by ES6:

const useProxy = (initialObj) => {
// State to trigger rerender when the proxy state changes
const [, dispatch] = useState(initialObj);
// State to hold the proxied object using the Proxy API
const [obj] = useState(
new Proxy(initialObj, {
get: function() {
// Using Reflect.get to access property values
return Reflect.get(...arguments);
},
set: function(obj, prop, value) {
// Updating the state only if the property value changes
if (obj[prop] !== value) {
obj[prop] = value;
// Trigger a state update with a shallow copy of the proxied object
dispatch({ ...obj });
}
return true;
},
})
);
// Return the proxied object
return obj;
}
Creating a proxied state object

The preceding custom useProxy hook takes a similar approach to the useCurrent hook and stores the initialObj into a state but at the same time creates another special object with the Proxy. Without going into too much ...