Skip to content
usefy

useSet

State & data

A React hook for managing Set state with immutable updates

Install

$ npm install @usefy/use-set

Quick 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

ParameterTypeDefaultDescription
initialStateSetInitializer<T>emptyA Set, an iterable of values, or a factory returning one (evaluated once)

Returns [set, actions]

ItemTypeDescription
setReadonlySet<T>Current set. Read via has/size/iteration
actionsUseSetActions<T>Stable action handlers (see below)

Actions

ActionSignatureDescription
add(value: T) => voidAdd a value. Adding an existing value is a no-op
remove(value: T) => voidRemove a value. Removing an absent value is a no-op
toggle(value: T, force?: boolean) => voidFlip membership, or set it explicitly with force (true = add, false = remove)
has(value: T) => booleanWhether the set contains a value (stable, always reflects latest state)
clear() => voidRemove all values. Clearing an empty set is a no-op
reset() => voidRestore the initial values (a fresh copy)

The returned set is a ReadonlySet, so calling set.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.

More in state & data