Last active
May 18, 2020 14:22
-
-
Save TianyiLi/ec2049ed6d202958d87598d2758a136f to your computer and use it in GitHub Desktop.
react-map-and-set-hooks-sample
This file contains 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 { useState, useMemo, useCallback } from 'react'; | |
interface StableActions<K> { | |
add: (key: K) => void; | |
remove: (key: K) => void; | |
reset: () => void; | |
} | |
interface Actions<K> extends StableActions<K> { | |
has: (key: K) => boolean; | |
} | |
function useSet<K>(initialValue?: Iterable<K>): [Set<K>, Actions<K>] { | |
const initialSet = useMemo<Set<K>>( | |
() => (initialValue === undefined ? new Set() : new Set(initialValue)) as Set<K>, | |
[initialValue] | |
); | |
const [set, setSet] = useState(initialSet); | |
const stableActions = useMemo<StableActions<K>>( | |
() => ({ | |
add: key => setSet(prevSet => new Set([...Array.from(prevSet), key])), | |
remove: key => setSet(prevSet => new Set(Array.from(prevSet).filter(i => i !== key))), | |
reset: () => setSet(initialSet), | |
}), | |
[setSet] | |
); | |
const utils = { | |
has: useCallback(key => set.has(key), [set]), | |
...stableActions, | |
} as Actions<K>; | |
return [set, utils]; | |
}; | |
export default useSet; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment