react-use-set
Use Set
-like API with React hook.
Instsall
Install react-use-set
npm package
npm i react-use-set
Usage
Get a Set-like object from useSet()
hook.ß
import { useSet } from "react-use-set"
const set = useSet()
It's got some Set methods and properties like
add
(enhanced)delete
(enhanced)clear
size
Along with additional utils like
Learn more in API section.
API
set.add(...values)
Calling this method triggers a re-render.
Add values to the Set. Multiple values are supported.
const set = useSet([1, 2, 3])
set.add(4)
set.add(5, 6)
set.delete(...values)
Calling this method triggers a re-render.
Remove values from the Set. Multiple values are supported.
const set = useSet([1, 2, 3])
set.delete(1, 2)
set.has(value)
Check whether a value exists in Set.
const set = useSet([1, 2, 3])
set.has(1)
set.has(4)
set.toggle(value)
Calling this method triggers a re-render.
If value
exists in the Set, remove it, otherwise add it.
const set = useSet([1, 2, 3])
set.toggle(2)
set.toggle(4)
This is useful when you want to store selected options on a list.
const selectedValues = useSet()
options.map((option) => (
<Checkbox onChange={() => selectedValues.toggle(option.value)} />
))
set.clear()
Calling this method triggers a re-render.
Remove all values from the Set.
const set = useSet([1, 2, 3])
set.clear()
set.size
Return the number of values in the Set.
const set = useSet([1, 2, 3])
set.size
set.toArray()
Return the values in the Set as an array.
const set = useSet([1, 2, 3])
set.toArray()
This is useful when you want to display a list of selected options.
<ol>
Selected options ({selectedValues.size})}):
{selectedValues.toArray().map((value) => (
<li key={value}>{value}</li>
))}
</ol>
set.sync(values)
Calling this method triggers a re-render.
Reset the Set with the given values.
const set = useSet([1, 2, 3])
set.sync([4, 5, 6])
License
MIT © Doma