Skip to Content
ohooks

useSelection

Manages single or multi-item selection state with range selection and bulk toggle helpers.

Loading preview...

The useSelection hook manages item selection for data tables, lists, and galleries, supporting key extraction (getKey), bulk selection (selectAll, clearSelection, toggleAll), Shift+Click range selection (selectRange), and computed isAllSelected / isPartiallySelected flags for indeterminate header checkboxes.

Installation

pnpm dlx shadcn@latest add https://ohooks.vercel.app/r/useSelection.json

Usage

Examples

Data Table with Indeterminate Header Checkbox

Use isAllSelected, isPartiallySelected, and toggleAll to wire up a master checkbox alongside row checkboxes.

Shift+Click Range Selection

Call selectRange(key) when the user holds the Shift key to select every item between the last interacted item and the clicked item.

API Reference

UseSelectionOptions

Configuration options for key extraction, single/multiple mode, and controlled/uncontrolled selection keys.

Property
Specification
getKey?
functiondefault:s to identity
Extracts a unique key for each item
multiple?
uniondefault:true
Allow selecting multiple items simultaneously
value?
array
Controlled array of selected keys.
defaultValue?
arraydefault:[]
Initial selected keys in uncontrolled mode
onChange?
function
Callback fired whenever the selected keys change.

UseSelectionReturn

Selection state, flags, and helper methods returned by the hook.

Property
Specification
selectedKeys
array
Array of currently selected item keys.
selectedSet
object
Set of currently selected item keys for O(1) lookups.
selectedItems
array
Array of items from items whose keys are currently selected.
isSelected
function
Returns true if key is currently selected.
isAllSelected
union
Whether every item in items is selected.
isPartiallySelected
union
Whether some, but not all, items in items are selected.
isNoneSelected
union
Whether zero items in items are selected.
select
function
Selects the item with the given key.
deselect
function
Deselects the item with the given key.
toggle
function
Toggles selection for the given key.
selectRange
function
Selects all items between fromKey and toKey inclusive.
selectAll
function
Selects all items in items (when multiple is true).
clear
function
Clears all selected keys.
toggleAll
function
Selects all items if not all are selected, otherwise clears the selection.
setSelectedKeys
function
Replaces the entire selection with keys.