useSet
State & dataA React hook for managing Set state with immutable updates
Install
$ npm install @usefy/use-setQuick start
useSet.tsx
import { useSet } from "@usefy/use-set";
function ItemList({ items }: { items: Item[] }) {
const [selected, { toggle, has }] = useSet<string>();
return (
<ul>
{items.map((item) => (
<li key={item.id}>
<label>
<input
type="checkbox"
checked={has(item.id)}
onChange={() => toggle(item.id)}
/>
{item.name}
</label>
</li>
))}
</ul>
);
}API reference
useSet<T>(initialState?)
Returns a tuple of the current read-only set and a stable actions object.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialState | SetInitializer<T> | empty | A Set, an iterable of values, or a factory returning one (evaluated once) |
Returns [set, actions]
| Item | Type | Description |
|---|---|---|
set | ReadonlySet<T> | Current set. Read via has/size/iteration |
actions | UseSetActions<T> | Stable action handlers (see below) |
Actions
| Action | Signature | Description |
|---|---|---|
add | (value: T) => void | Add a value. Adding an existing value is a no-op |
remove | (value: T) => void | Remove a value. Removing an absent value is a no-op |
toggle | (value: T, force?: boolean) => void | Flip membership, or set it explicitly with force (true = add, false = remove) |
has | (value: T) => boolean | Whether the set contains a value (stable, always reflects latest state) |
clear | () => void | Remove all values. Clearing an empty set is a no-op |
reset | () => void | Restore the initial values (a fresh copy) |
The returned
setis aReadonlySet, so callingset.add(...)directly is a TypeScript error. Use the actions — mutating the set in place would bypass React state and break re-renders.
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.