Skip to main content
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

Parameter explanation:
  • allIds: Array of all keys on current page (e.g., [1, 2, 3, 4, 5])
  • defaultSelectedKeys: Initial selection state (optional, default: [])

Individual Item Selection

How it works:
  • getSelected(key): Returns true if key is selected, false otherwise
  • toggle(key): Toggle selection state

Select All/Deselect All

How it works:
  • isAllSelected: Whether all items on current page are selected
  • selectAll(): Select all items on current page
  • deselectAll(): Deselect all selections

Shift+Click Range Selection

How it works:
  1. Normal click: Toggle individual item selection
  2. Shift+click: Select all items from last selection to current position
How Shift+click workshandleCheckboxClick 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.
Validation logic:
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.
Why use Map:
  • 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.