-
-
Notifications
You must be signed in to change notification settings - Fork 3.3k
Expand file tree
/
Copy pathuseSet.ts
More file actions
48 lines (42 loc) · 1.09 KB
/
useSet.ts
File metadata and controls
48 lines (42 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import { useRef, useState } from 'react';
export interface StableActions<K> {
add: (key: K) => void;
remove: (key: K) => void;
toggle: (key: K) => void;
reset: () => void;
clear: () => void;
}
export interface Actions<K> extends StableActions<K> {
has: (key: K) => boolean;
}
const useSet = <K>(initialSet = new Set<K>()): [Set<K>, Actions<K>] => {
const [, forceUpdate] = useState({});
const setRef = useRef(new Set(initialSet));
const actions: Actions<K> = {
add: (item: K) => {
setRef.current.add(item);
forceUpdate({});
},
remove: (item: K) => {
setRef.current.delete(item);
forceUpdate({});
},
toggle: (item: K) => {
setRef.current.has(item)
? setRef.current.delete(item)
: setRef.current.add(item);
forceUpdate({});
},
reset: () => {
setRef.current = new Set(initialSet);
forceUpdate({});
},
clear: () => {
setRef.current.clear();
forceUpdate({});
},
has: (item: K) => setRef.current.has(item),
};
return [setRef.current, actions];
};
export default useSet;