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 changesconst [, dispatch] = useState(initialObj);// State to hold the proxied object using the Proxy APIconst [obj] = useState(new Proxy(initialObj, {get: function() {// Using Reflect.get to access property valuesreturn Reflect.get(...arguments);},set: function(obj, prop, value) {// Updating the state only if the property value changesif (obj[prop] !== value) {obj[prop] = value;// Trigger a state update with a shallow copy of the proxied objectdispatch({ ...obj });}return true;},}));// Return the proxied objectreturn obj;}
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 ...