useSelection is a hook that manages multi-select functionality via checkboxes in list pages. It provides features like Shift+click range selection and select all/deselect all.
Core Features
Multi-select
Manage individual/all selectionSet-based efficient state
Range Selection
Shift+click supportSelect consecutive items at once
Auto Validation
Auto cleanup on page changeKeep only existing items
Type Safety
Generic type supportUse any type as key
Basic Usage
Import and Initialization
allIds: Array of all keys on current page (e.g.,[1, 2, 3, 4, 5])defaultSelectedKeys: Initial selection state (optional, default:[])
Individual Item Selection
getSelected(key): Returnstrueif key is selected,falseotherwisetoggle(key): Toggle selection state
Select All/Deselect All
isAllSelected: Whether all items on current page are selectedselectAll(): Select all items on current pagedeselectAll(): Deselect all selections
Shift+Click Range Selection
- Normal click: Toggle individual item selection
- Shift+click: Select all items from last selection to current position
How Shift+click works
handleCheckboxClick remembers the last click index and selects all items in between when Shift+clicking.Real-world Examples
Complete Table Implementation
Auto Validation on Page Change
useSelection automatically validates selection state when allIds changes.
Why is auto validation needed?When navigating pages or changing filters,
rows changes. Items selected on the previous page may not exist on the new page, so invalid selections are automatically removed.Operations with Selected Items
Advanced Usage
Initial Selection State
Saving Selection State
Conditional Selection Restrictions
Internal Structure
useSelection manages selection state with a Map<T, boolean> structure.
- O(1) time complexity for fast lookups
- No type constraints on keys (number, string, object all possible)
- More extensible than Set (can store additional metadata)
Type Safety
useSelection can specify key type with generics.
Cautions
1. Always provide allIds
2. To maintain selection across page changes
By default, selection is reset when navigating pages. Separate management is needed to maintain it.3. When using handleCheckboxClick
handleCheckboxClick should be connected to <td> or checkbox container.
Related Documentation
- useListParams - Use with list filtering
- Table Component - Table UI
- Building List Page - Complete example