Skip to content

Instantly share code, notes, and snippets.

@Maxondria
Created March 21, 2023 14:46
Show Gist options
  • Save Maxondria/7bb0a7c6cbc33bc4ffbdb300ac591f0b to your computer and use it in GitHub Desktop.
Save Maxondria/7bb0a7c6cbc33bc4ffbdb300ac591f0b to your computer and use it in GitHub Desktop.
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