Skip to content

Instantly share code, notes, and snippets.

@TianyiLi
Created May 18, 2020 14:55
Show Gist options
  • Save TianyiLi/fb275688e9ff31bb463068e84619b77e to your computer and use it in GitHub Desktop.
Save TianyiLi/fb275688e9ff31bb463068e84619b77e to your computer and use it in GitHub Desktop.
useSet
import { useState, Dispatch, SetStateAction, useMemo } from 'react';
const reactiveKeys = ['add', 'clear', 'delete'];
const reactive = <K>(set: Set<K>, setSet: Dispatch<SetStateAction<Set<K>>>) => {
const _proxy = Proxy.revocable(set, {
get(target, value: keyof Set<K>) {
if (reactiveKeys.includes(value)) {
return (arg: K) => {
target[value as 'add' | 'clear' | 'delete'].bind(target)(arg);
setSet(new Set([...target]));
_proxy.revoke();
};
} else {
return typeof target[value] === 'function'
? (target[value] as Function).bind(target)
: target[value];
}
},
});
return _proxy.proxy;
};
export const useSet = <K>(initial?: Iterable<K>) => {
const [set, setSet] = useState(new Set(initial));
return useMemo(() => reactive(set, setSet), [set]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment