Skip to content

useSelections

Multi-select helpers for a collection.

Multi-select helpers for a collection.

Import

import { useSelections } from '@kamod-ch/hooks'

Live demo

Basic demo

Multi-select helpers for a collection.

Tasks

Selected: none

import { useSelections } from '@kamod-ch/hooks'

const items = ['Docs', 'Tests', 'Release']

export default function UseSelectionsDemo() {
  const selection = useSelections(items)

  return (
    <div>
      <fieldset>
        <legend>Tasks</legend>
        {items.map((item) => (
          <label key={item} class="demo-option">
            <input type="checkbox" checked={selection.isSelected(item)} onInput={() => selection.toggle(item)} />
            {item}
          </label>
        ))}
      </fieldset>
      <p><strong>Selected:</strong> {selection.selected.join(', ') || 'none'}</p>
      <div class="demo-actions">
        <button type="button" onClick={selection.selectAll}>Select all</button>
        <button type="button" onClick={selection.clearAll}>Clear</button>
      </div>
    </div>
  )
}

API

TypeScript signature
import type { Key } from 'preact';
export interface Options<T> {
    defaultSelected?: T[];
    itemKey?: string | ((item: T) => Key);
}
declare function useSelections<T>(items: T[], options?: T[] | Options<T>): {
    readonly selected: T[];
    readonly noneSelected: boolean;
    readonly allSelected: boolean;
    readonly partiallySelected: boolean;
    readonly setSelected: import("preact/hooks").Dispatch<import("preact/hooks").StateUpdater<T[]>>;
    readonly isSelected: (item: T) => boolean;
    readonly select: (this: unknown, item: T) => void;
    readonly unSelect: (this: unknown, item: T) => void;
    readonly toggle: (this: unknown, item: T) => void;
    readonly selectAll: (this: unknown) => void;
    readonly unSelectAll: (this: unknown) => void;
    readonly clearAll: (this: unknown) => void;
    readonly toggleAll: (this: unknown) => void;
};
export default useSelections;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.