Last active
February 16, 2022 21:14
-
-
Save KacperKozak/9b6cbd67fd18cea68d87530fb056f2e8 to your computer and use it in GitHub Desktop.
React useSet hook
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 { uniq, xor } from 'lodash' | |
import { useMemo, useState } from 'react' | |
export const useSet = <T>(initial: T[] | (() => T[]) = []) => { | |
const [state, setState] = useState(initial) | |
return useMemo( | |
() => ({ | |
values: state, | |
size: state.length, | |
has: (item: T) => state.includes(item), | |
set: (items: T[]) => setState(items), | |
add: (item: T) => setState(items => uniq([...items, item])), | |
delete: (item: T) => setState(items => items.filter(i => i !== item)), | |
toggle: (item: T) => setState(items => xor(items, [item])), | |
clear: () => setState([]), | |
}), | |
[state] | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment