useSelectionui-interaction
useSelection
NewSSR SAFEManages single, multi, and batch selection states with Set-based O(1) lookups and range selection.
$ pnpm dlx shadcn@latest add @byphongphan/use-selectionRequires
@byphongphan in components.jsonuse-selection.tsx
Loading preview...
Installation
$ pnpm dlx shadcn@latest add @byphongphan/use-selectionRequires
@byphongphan in components.jsonUsage
Table Batch Selection
Shift + Click Range Selection
Features
- O(1) Set Performance: Uses native JavaScript
Set<SelectionKey>internally for instant constant-time selection lookups. - Tri-State Header Checkbox: Accurately computes
isAllSelectedandisPartiallySelectedfor indeterminate state handling in tables and list headers. - Continuous Range Selection: Built-in
selectRange(fromKey, toKey)allows implementing desktop-style Shift + Click multi-row selection in just one line. - Derived Selected Items: Automatically returns
selectedItemsarray synchronized withselectedKeys. - Flexible Key Resolution: Defaults to
item.id ?? item.key ?? item, or provide a customgetKeyextractor for custom data models.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
items | readonly T[] | — | The array of items available for selection. |
options.getKey | (item: T) => SelectionKey | (item) => item.id ?? item.key ?? item | Custom function to extract a unique string or number identifier. |
options.initialSelected | SelectionKey[] | Set<SelectionKey> | — | Initial keys selected on mount. |
Returns
Returns a UseSelectionReturn<T> object:
| Property | Type | Description |
|---|---|---|
selectedKeys | Set<SelectionKey> | Active Set containing all selected identifiers. |
selectedItems | T[] | Array of full item objects corresponding to the selected keys. |
selectedCount | number | Number of currently selected items (selectedKeys.size). |
isSelected | (key: SelectionKey) => boolean | Checks whether a specific item key is selected. |
isAllSelected | boolean | Whether every item in the dataset is selected. |
isPartiallySelected | boolean | Whether at least one item is selected, but not all (indeterminate state). |
select | (keys: SelectionKey | SelectionKey[]) => void | Selects one or multiple keys. |
deselect | (keys: SelectionKey | SelectionKey[]) => void | Deselects one or multiple keys. |
toggle | (key: SelectionKey) => void | Inverts the selection status of a single key. |
selectAll | () => void | Selects every item in the dataset. |
clear | () => void | Deselects all items. |
toggleAll | () => void | Toggles between selecting all and deselecting all items. |
selectRange | (fromKey: SelectionKey, toKey: SelectionKey) => void | Selects all items between fromKey and toKey inclusive (Shift-Click). |
setSelectedKeys | Dispatch<SetStateAction<Set<SelectionKey>>> | Direct state setter for manual overrides. |