use-row-selection.ts
Overview
The use-row-selection.ts file provides React hooks to manage and interact with row selection states, primarily designed for use in data table components. It utilizes React's state and memoization hooks to enable efficient selection handling, including selection tracking, clearing, and retrieving selected item identifiers. This file is especially useful when integrating with @tanstack/react-table, a popular React table library, and leverages lodash for utility functions.
Exports
useRowSelection
Purpose
useRowSelection is a custom React hook that manages the state of selected rows in a table or list. It provides methods to clear the selection, access the current selection state, and retrieve the count of selected rows.
Function Signature
function useRowSelection(): {
rowSelection: RowSelectionState;
setRowSelection: React.Dispatch<React.SetStateAction<RowSelectionState>>;
rowSelectionIsEmpty: boolean;
clearRowSelection: () => void;
selectedCount: number;
}
Parameters
None
Returns
An object containing:
rowSelection: The current row selection state, keyed by row indices as strings. Its type isRowSelectionStatefrom@tanstack/react-table.setRowSelection: A setter function to update the row selection state.rowSelectionIsEmpty: A boolean indicating if no rows are currently selected.clearRowSelection: A function to clear all selected rows.selectedCount: The number of currently selected rows.
Usage Example
import { useRowSelection } from './use-row-selection';
function MyTableComponent() {
const {
rowSelection,
setRowSelection,
rowSelectionIsEmpty,
clearRowSelection,
selectedCount,
} = useRowSelection();
// Use these to manage selection state in your table UI
}
Implementation Details
Uses React's
useStateto hold the selection state, which is an object mapping row indices (as strings) totrueorfalseto represent selection.clearRowSelectionusesuseCallbackto memoize the function that resets selection.selectedCountis memoized withuseMemo, counting the keys in therowSelectionobject.rowSelectionIsEmptyuses Lodash'sisEmptyutility for efficient emptiness check.
UseRowSelectionType
This is a TypeScript utility type representing the return type of the useRowSelection hook.
export type UseRowSelectionType = ReturnType<typeof useRowSelection>;
This can be used for typing variables or props that consume the row selection state and methods.
useSelectedIds
Purpose
useSelectedIds is a generic React hook to retrieve the identifiers (id properties) of selected items from a given list, based on the row selection state.
Function Signature
function useSelectedIds<T extends Array<{ id: string }>>(
rowSelection: RowSelectionState,
list: T,
): { selectedIds: string[] }
Parameters
rowSelection(RowSelectionState): The current selection state, typically obtained fromuseRowSelection.list(T): An array of objects each having anidstring property. This represents the full dataset or rows being displayed or managed.
Returns
selectedIds: An array of strings containing theidvalues of the selected rows.
Usage Example
import { useSelectedIds } from './use-row-selection';
const data = [
{ id: 'a1', name: 'Item A' },
{ id: 'b2', name: 'Item B' },
{ id: 'c3', name: 'Item C' },
];
const { selectedIds } = useSelectedIds(rowSelection, data);
console.log(selectedIds); // e.g. ['a1', 'c3'] if those rows are selected
Implementation Details
Uses
useMemoto efficiently compute the selected IDs only whenrowSelectionorlistchanges.Converts the keys of the
rowSelectionobject (which are string indices) to numbers, filters thelistby those indices, then maps the filtered list to extract theidvalues.This approach assumes the
rowSelectionkeys correspond directly to the index positions of items in thelist.
Important Implementation Notes
Row Selection State Format: The selection state stored in
rowSelectionuses string keys representing row indices, which aligns with the internal representation used by@tanstack/react-table. This design makes it efficient to toggle selections without needing to handle complex data structures.Performance Optimization: The hooks use React's
useMemoanduseCallbackto prevent unnecessary recalculations and re-renders when selection state changes, which is critical for performance in large tables.Generics and Type Safety:
useSelectedIdsuses TypeScript generics to ensure that the list items have anidproperty, enhancing type safety when retrieving selected IDs.
Interaction with Other Parts of the System
Integration with
@tanstack/react-table: TheRowSelectionStatetype is imported from@tanstack/react-table, indicating this hook is designed to be compatible with the selection model used in that table library.Utility Functions: Uses
lodash'sisEmptyto check if the row selection object has any selected rows.React Components: Designed to be used within functional React components that render tables or lists, managing selection state in a predictable and encapsulated manner.
Data Flow: The selection state (
rowSelection) is maintained internally but can be passed down or lifted up via props or context for synchronization with other components or global state.
Mermaid Diagram
classDiagram
class useRowSelection {
+rowSelection: RowSelectionState
+setRowSelection: Dispatch<SetStateAction<RowSelectionState>>
+rowSelectionIsEmpty: boolean
+clearRowSelection(): void
+selectedCount: number
}
class useSelectedIds~T~ {
+selectedIds: string[]
}
Summary
The use-row-selection.ts file encapsulates logic for handling row selection in React table components, offering a clean and performant API for managing selection state and extracting selected item IDs. It is well-suited for integration with @tanstack/react-table and follows best practices with React hooks and TypeScript typings. This file simplifies selection management, enabling developers to focus on building responsive and intuitive UI components.