StateBeginnerFully SSR-safehooks/state/useSet.ts

useSet

Immutable Set state API.

Import

TypeScript
import { useSet } from '@/hooks';

API

Signature

useSet<T>(initial?) → [Set, actions]

When to use

Use useSet instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Fully SSR-safe. Pure React state.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useSet
Editor
function Tags() {
  const [tags, set] = useSet<string>(['react']);
  return (
    <button onClick={() => set.toggle('next')}>
      has next? {String(set.has('next'))} · size {tags.size}
    </button>
  );
}
Preview

Implementation source

Full library source for useSet — copy into your project when you are not installing a package yet.

hooks/state/useSet.ts
import { useCallback, useState } from 'react';

export interface UseSetActions<T> {
  add: (item: T) => void;
  remove: (item: T) => void;
  toggle: (item: T) => void;
  has: (item: T) => boolean;
  clear: () => void;
  reset: () => void;
  set: (next: Set<T> | T[]) => void;
}

/** Set-backed state with immutable updates. */
export function useSet<T>(
  initialValue?: Iterable<T>,
): [Set<T>, UseSetActions<T>] {
  const [set, setSet] = useState(() => new Set(initialValue));

  const actions: UseSetActions<T> = {
    add: useCallback((item) => {
      setSet((prev) => {
        if (prev.has(item)) return prev;
        const next = new Set(prev);
        next.add(item);
        return next;
      });
    }, []),
    remove: useCallback((item) => {
      setSet((prev) => {
        if (!prev.has(item)) return prev;
        const next = new Set(prev);
        next.delete(item);
        return next;
      });
    }, []),
    toggle: useCallback((item) => {
      setSet((prev) => {
        const next = new Set(prev);
        if (next.has(item)) next.delete(item);
        else next.add(item);
        return next;
      });
    }, []),
    has: useCallback((item) => set.has(item), [set]),
    clear: useCallback(() => setSet(new Set()), []),
    reset: useCallback(() => setSet(new Set(initialValue)), [initialValue]),
    set: useCallback((next) => {
      setSet(next instanceof Set ? new Set(next) : new Set(next));
    }, []),
  };

  return [set, actions];
}

Copy-paste example

useSet.example.tsx
'use client';

import { useSet } from '@/hooks';

export function Tags() {
  const [tags, set] = useSet<string>(['react']);
  return (
    <button onClick={() => set.toggle('next')}>
      has next? {String(set.has('next'))} · size {tags.size}
    </button>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Keep state setters stable; prefer action helpers over manual setState spreads.
  • Source of truth: open hooks/state/useSet.ts for implementation details