gridcn2.0.0
Types and hooks

Store hooks

Look up each hook that reads grid state or reaches the grid from code, with its return value and the page that uses it.

Store hooks read the state of one grid. Inside a DataGridProvider they work. Outside it, they throw. Two items differ: useDataGridStoreProps runs outside the provider and creates the store, and createDataGridSelector is a factory that you call once at module scope. Import them from @/components/data-grid/data-grid. A hook that reads state subscribes to its own slice, so a component re-renders only when that slice changes.

GroupHooks
Handle and actionsuseDataGridActions, useDataGridApi, useDataGridStoreProps, useDataGridScrollToCell, useDataGridScrollToCellAt, useDataGridClipboard
Rows and addressesuseDataGridViewIndex, useDataGridViewStale, useDataGridRow, useDataGridRowId, useDataGridRowIds, useDataGridRowIdToViewRow
Cells and editinguseDataGridReadOnly, useDataGridActiveCell, useDataGridActiveColumn, useDataGridEditing, useDataGridCellEditingError, useDataGridCellState, useDataGridRowCellState, useDataGridCellTypes
SelectionuseDataGridSelection, useDataGridGetSelectionValues, useDataGridSelectedRows, useDataGridHiddenCheckedCount
ColumnsuseDataGridVisibleColumns, useDataGridAllColumns, useDataGridIsColumnHidden, useDataGridColumnWidth, useDataGridColumnWidths
Sort, filter, and searchuseDataGridSortState, useDataGridFilterState, useDataGridSearchText
Labels, keys, and savesuseDataGridLabels, useDataGridKeymap, useDataGridCellErrors, useDataGridRowSaveStatus, useDataGridPendingSaveCount, useDataGridGatePending
Typed selectorcreateDataGridSelector
Typed hookscreateDataGridHooks

Handle and actions

Hooks that reach the grid from code.

HookReturnsMeaning
useDataGridActionsDataGridActionsThe actions object. Its identity never changes, so the hook never re-renders. Actions A to Z lists each action.
useDataGridApiDataGridApi<TData>The imperative handle. useDataGridApi(ref?) returns the handle. Pass a ref to also assign it to that ref. Its identity is stable for the grid's lifetime.
useDataGridStoreProps{ store, actions }Creates the store outside the provider. Feed store to DataGridProvider.
useDataGridScrollToCell(ref: CellRef) => voidScrolls a cell into view. It does nothing before DataGridRoot mounts, and warns in development for a ref that does not resolve.
useDataGridScrollToCellAt(coord: ViewCoord) => voidThe same scroll for a view coordinate.
useDataGridClipboardUseDataGridClipboardResultReturns copy, cut, and pasteFromClipboard. copy and cut resolve "ok", "fallback", "failed", or "no-selection". cut also resolves "refused" while a cell editor is open. pasteFromClipboard resolves a PasteFromClipboardResult: "ok", "permission-denied", "empty" (the clipboard holds no text), or "refused" (the grid started no paste, as Clipboard lists). The hook takes an optional { sanitizeFormulas }. Its default is the sanitizeClipboardFormulas prop.

These actions have no feature page:

  • setActiveCellAt sets the active cell at a ViewCoord, or clears it with null.
  • extendToAt extends the selection to the cell at a ViewCoord.
  • extendSelection grows the selection by one cell in a direction ("up", "down", "left", "right"), or to the edge with { toEdge: true }. It does nothing when enableRangeSelection is false.
  • pushRangeAt adds a range to the cell at a ViewCoord, like a Ctrl/Cmd+click. Without enableMultiRange, it selects the cell like a click.
  • checkRowRange checks or unchecks the rows from the anchor row to a view row index. It does nothing when enableRowSelection is false.
  • clearCellSelection clears the cell range and the selected columns and keeps the checked rows.
  • commitCellEdit validates and commits the value of the open edit, then moves the active cell by an optional { dx, dy }. A rejected value keeps the edit open and sets the editing error.
  • commitCellValueAt validates and writes a value at a ViewCoord without an edit session, like a checkbox click.
  • deleteSelection clears every writable cell of the selection to the empty value of its cell type, as one change.
  • applyCellUpdates writes a list of { viewRowIndex, columnId, value } updates as one change with a source. It skips read-only cells and unchanged values. Without rejected and warnings, it runs the column validate like a paste. Pass them to report your own results instead.

Rows and addresses

Hooks that read rows. State and view index explains the addresses.

HookReturnsMeaning
useDataGridViewIndexreadonly number[]The viewIndex array: the data index of the row at each view index.
useDataGridViewStalebooleantrue while rows keep an old view index after a write. actions.reconcileView() clears it. With useDataGridServerRows, it stays true until the server answer delivers the stale rows again.
useDataGridRowTData | undefinedThe row at a view index. Pass TData as a type argument. It re-renders only when that row changes.
useDataGridRowIdstring | undefinedThe row id at a view index. A row that scroll mode has not loaded returns a placeholder id. An index outside the view returns undefined.
useDataGridRowIds(string | undefined)[]The row ids for a list of view indexes, in one subscription.
useDataGridRowIdToViewRowReadonlyMap<string, number>A map from row id to view index. The map keeps its identity across writes that move no row.

Cells and editing

Hooks that read the active cell and the edit session.

HookReturnsMeaning
useDataGridReadOnlybooleanThe readOnly flag of the provider. It is correct on the first render, also on the server.
useDataGridActiveCellViewCoord | nullThe active cell, or null.
useDataGridActiveColumnnumber | nullThe view column of the active cell. Vertical moves do not re-render the subscriber.
useDataGridEditingThe open edit or nullThe edit in progress, with its row id and column id.
useDataGridCellEditingErrorstring | nullThe live validation error of the cell at a ViewCoord while that cell is in edit. Every other cell gets null.
useDataGridCellStateDataGridCellStateOne subscription for one cell: isActive, isSelected, isEditing, initialText, editSession, isSearchMatch, and cellError.
useDataGridRowCellStateDataGridRowCellStateOne subscription for one view row. It covers the active and editing columns of the row, its selectedColRanges, its saveStatus, its stale flag, and its search match, error, and flashing columns.
useDataGridCellTypesRecord<string, CellType>The resolved cell type registry: the built-in cell types merged with your cellTypes prop. A null entry removes a built-in type.

Show the active cell and the read-only flag in a status line:

import {
  useDataGridActiveCell,
  useDataGridReadOnly,
} from "@/components/data-grid/data-grid";

export function CellStatus() {
  const cell = useDataGridActiveCell();
  const readOnly = useDataGridReadOnly();
  return (
    <span>
      {cell ? `Row ${cell.row + 1}, column ${cell.col + 1}` : "No active cell"}
      {readOnly ? " (read only)" : ""}
    </span>
  );
}

Selection

Hooks that read the selection. Selection model explains the channels.

HookReturnsMeaning
useDataGridSelectionGridSelectionThe selection in view indexes. The selection prop, onSelectionChange, and getSelection() use ids (SelectionState), so they survive a sort or a filter.
useDataGridGetSelectionValues() => unknown[][]A stable callback. Each call reads the values of the main range at call time, or [] without a range.
useDataGridSelectedRowsDataGridSelectedRowsThe checked rows as a value for a bulk action. Mode "ids" holds ids and count. Mode "allMatching" holds excludedIds, count (or null), and the spec to send. See Select server rows.
useDataGridHiddenCheckedCountnumberThe count of checked rows that left the view (a filter, a page change, or a window move) and checkedRowsLifetime="across-filters" remembers. It is 0 after selectAllMatching().

Columns

Hooks that read column state. Column visibility uses them.

HookReturnsMeaning
useDataGridVisibleColumnsreadonly ColumnDefOf<TData>[]The visible columns in display order: start-pinned, unpinned, end-pinned.
useDataGridAllColumnsreadonly ColumnDefOf<TData>[]Every column, hidden ones included, in column order.
useDataGridIsColumnHiddenbooleanWhether a column id is hidden.
useDataGridColumnWidthnumber | undefinedThe width override of a column in pixels, or undefined.
useDataGridColumnWidths(number | undefined)[]The width overrides of a list of column ids, in one subscription.

Sort, filter, and search

Hooks that read the spec. Server rows contract sends it to a backend.

HookReturnsMeaning
useDataGridSortStateSortSpec[]The active sorts.
useDataGridFilterStateFilterNode[]The active filter tree.
useDataGridSearchTextstringThe quick-search text.

Labels, keys, and saves

Hooks for text, keys, and server results.

HookReturnsMeaning
useDataGridLabelsDataGridLabelsThe labels: the defaults merged with your labels prop. useOptionalDataGridLabels from @/components/data-grid/data-grid-sdk returns the same labels, or null outside a provider.
useDataGridKeymapKeymapThe effective keymap: defaults, plugin keymaps, then your keymap prop. It leaves out a binding that never matches: an unknown modifier, an unknown key name, or an empty key. An action with no live binding reads [].
useDataGridCellErrorsReadonlyMap<string, string>The map of cell errors, keyed "rowId:columnId". The server sets them with setCellErrors, and a column with validationMode: "warn" sets them on a value it accepts with a warning. A cell renders its own error through useDataGridCellState.
useDataGridRowSaveStatusRowSaveStatus | undefined"saving" while the onSave promise of the row is pending, "failed" after a refusal, else undefined.
useDataGridPendingSaveCountnumberThe count of onSave promises that have not settled.
useDataGridGatePendingReadonlySet<GateName>The names of the gates whose promise has not settled. See Cancel async gates.

createDataGridSelector

createDataGridSelector<TData>() returns a hook that reads any slice of the store. Create the hook once at module scope. The selector receives the store state with data typed as readonly TData[]. The hook takes (selector, eq?). eq defaults to Object.is and decides when the component re-renders.

Sum a column in a component below the provider:

import { useMemo } from "react";
import { createDataGridSelector } from "@/components/data-grid/data-grid";

type Order = { id: string; total: number };

const useOrderSelector = createDataGridSelector<Order>();

export function TotalBadge() {
  const data = useOrderSelector((state) => state.data);
  const total = useMemo(
    () => data.reduce((sum, row) => sum + (row?.total ?? 0), 0),
    [data],
  );
  return <span>{total}</span>;
}

createDataGridHooks

createDataGridHooks<TData>() returns useDataGridApi, useDataGridRow, useDataGridVisibleColumns, useDataGridAllColumns, and useDataGridSelector, with the row type fixed. Call it once at module scope:

import { createDataGridHooks } from "@/components/data-grid/data-grid";

type Order = { id: string; total: number };

export const { useDataGridRow, useDataGridSelector } =
  createDataGridHooks<Order>();

export function FirstTotal() {
  const row = useDataGridRow(0);
  const count = useDataGridSelector((state) => state.data.length);
  return (
    <span>
      {row?.total} of {count} rows
    </span>
  );
}

On this page