Skip to content

Instantly share code, notes, and snippets.

@KacperKozak
Last active February 16, 2022 21:14
Show Gist options
  • Save KacperKozak/9b6cbd67fd18cea68d87530fb056f2e8 to your computer and use it in GitHub Desktop.
Save KacperKozak/9b6cbd67fd18cea68d87530fb056f2e8 to your computer and use it in GitHub Desktop.
React useSet hook
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