Created
March 21, 2023 14:46
-
-
Save Maxondria/7bb0a7c6cbc33bc4ffbdb300ac591f0b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useRef, useState } from 'react'; | |
export const useReactState = <T extends object>(initialState: T): T => { | |
const [, setState] = useState<number>(0); | |
const proxy = useRef( | |
new Proxy(initialState, { | |
set: (target, key, value) => { | |
if (!(key in target)) { | |
return false; | |
} | |
target[key as keyof T] = value; | |
setState((i) => i + 1); | |
return true; | |
}, | |
} as ProxyHandler<T>), | |
); | |
return proxy.current; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment