# Virtualization

> Row and column virtualization, scaled scrolling for millions of rows, measured row heights and the server-rendered initial range.

Canonical: https://salmonui.dev/docs/data-grid/virtualization

Rows and columns are virtualized by default whenever the grid has a height:
the DOM holds the visible cells plus a small
overscan on each edge, and the header stays sticky while
the body scrolls. Scrolling writes only to the DOM and a renderer
store, never to React state, which is what keeps a
100,000 × 100 grid smooth. A smaller row height shows more rows
per viewport.

`virtualization` is `true` by default; an object tunes it and `false`
renders every row and column. `height` (default 400 px) sets the viewport;
`height="auto"` grows the grid with its rows and turns row virtualization
off.

| Option | Default | Meaning |
| --- | --- | --- |
| `rows` | `true` | Row virtualization |
| `columns` | `true` | Column virtualization of the center (unpinned) zone |
| `rowOverscan` | 5 | Rows rendered beyond each edge of the viewport |
| `columnOverscan` | 2 | Center columns rendered beyond each edge |
| `maxScrollHeight` | 15,000,000 px | Physical scroll height cap; taller content is compressed |
| `skeletonRows` | `true` | Skeleton bars in rows that are not loaded yet |

```tsx
<DataGrid data={rows} columns={columns} height={600} rowHeight={32} virtualization={{ rowOverscan: 10 }} />
```

Percent column widths are resolved once per viewport width, so they work
under column virtualization.

### Live demo: 100,000 rows × 100 columns

Live demo: https://salmonui.dev/demos/data-grid/virtualization

Row and column virtualization with a sticky header, overscan settings, a smaller row height, percent widths under column virtualization, and scroll-to-row/column.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi } from '@salmonui/data-grid';
import { createWideRows, type WideRow } from '../../lib/fixtures';
import { createWideColumns } from '../../lib/wide';

const rows = createWideRows(100_000);
const columns = createWideColumns(100);

export default function VirtualizationDemo() {
  const api = useRef<DataGridApi<WideRow> | null>(null);
  const [range, setRange] = useState('');
  const readRange = () => {
    const current = api.current?.getRenderedRange();
    const cells = api.current?.element?.querySelectorAll('.salmon-data-grid-rows .salmon-data-grid-cell').length ?? 0;
    if (current) setRange(`rows ${current.rows.start}-${current.rows.end}, columns ${current.columns.start}-${current.columns.end}, ${cells} body cells in the DOM`);
  };
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.scrollToRow('50000', { align: 'center' })}>
          Scroll to row 50,000
        </Button>
        <Button variant="outline" onClick={() => api.current?.scrollToColumn('n80')}>
          Scroll to column 80
        </Button>
        <Button variant="outline" onClick={readRange}>
          Read rendered range
        </Button>
      </div>
      <DataGrid<WideRow>
        aria-label="100,000 rows by 100 columns"
        data={rows}
        columns={columns}
        height={420}
        rowHeight={32}
        locale="en-US"
        virtualization={{ rowOverscan: 6, columnOverscan: 2 }}
        ref={api}
      />
      <p className="demo-status" role="status">
        {range || 'Scroll the grid, then read the rendered range: the DOM only holds the viewport plus overscan.'}
      </p>
    </>
  );
}
```

## Millions of rows

Browsers cap element height at roughly 22 million pixels in some engines.
Beyond `virtualization.maxScrollHeight` the grid compresses the scroll range
and maps the scroll offset back to row positions, so every row stays
reachable. A percentage height needs a parent with a fixed height;
the grid observes its viewport size.

### Live demo: One million rows

Live demo: https://salmonui.dev/demos/data-grid/million-rows

36 million pixels of rows exceed the browser's element height limit; scaled scroll mapping keeps every row reachable. The grid fills a fixed-height parent.

`Demo.tsx`:

```tsx
'use client';

import { useRef } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi } from '@salmonui/data-grid';
import { createWideRows, type WideRow } from '../../lib/fixtures';
import { createWideColumns } from '../../lib/wide';

const rows = createWideRows(1_000_000);
const columns = createWideColumns(8);

export default function MillionRowsDemo() {
  const api = useRef<DataGridApi<WideRow> | null>(null);
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.scrollToRow('999999', { align: 'end' })}>
          Scroll to the last row
        </Button>
        <Button variant="outline" onClick={() => api.current?.scrollToRow('0')}>
          Back to the top
        </Button>
      </div>
      {/* A percentage height needs a parent with a fixed height. */}
      <div className="demo-fill">
        <DataGrid<WideRow> aria-label="One million rows" data={rows} columns={columns} height="100%" locale="en-US" ref={api} />
      </div>
    </>
  );
}
```

## Variable row heights

With `estimatedRowHeight` (an estimate in px) the grid measures rendered rows and corrects
offsets as it scrolls, so wrapped text and templates can produce
rows of different heights under virtualization. Fixed per-row
heights without measuring come from `getRowHeight(row)`. Row templates are
virtualized too (see Templates).

### Live demo: Wrapped text and measured row heights

Live demo: https://salmonui.dev/demos/data-grid/variable-row-height

Text wrapping for headers, content or both, with measured variable row heights under row virtualization.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { DataGrid, type DataGridColumn, type DataGridTextWrap } from '@salmonui/data-grid';
import { Select } from '@salmonui/dropdowns/select';
import { createOrders, type Order } from '../../lib/fixtures';

const orders = createOrders(5_000, 11);

const columns: DataGridColumn<Order>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer name as printed on the invoice', width: 140 },
  { field: 'note', header: 'Delivery note', width: 220 },
  { field: 'product', header: 'Product', width: 140 },
];

const modes: readonly DataGridTextWrap[] = ['both', 'content', 'header', false];
const MODE_OPTIONS = modes.map((mode) => ({ value: String(mode), label: mode === false ? 'off' : mode }));

export default function VariableRowHeightDemo() {
  const [wrap, setWrap] = useState<DataGridTextWrap>('both');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          Text wrap
          <Select aria-label="Text wrap" data={MODE_OPTIONS} value={String(wrap)} onValueChange={(value) => setWrap(modes.find((m) => String(m) === value) ?? false)} />
        </label>
      </div>
      {/* estimatedRowHeight switches to measured row heights; the key remounts on mode change. */}
      <DataGrid<Order>
        key={String(wrap)}
        aria-label="Orders with wrapped, variable-height rows"
        data={orders}
        columns={columns}
        height={380}
        estimatedRowHeight={36}
        textWrap={wrap}
        // The header row keeps a fixed height: give wrapped headers room for three lines.
        {...(wrap === 'header' || wrap === 'both' ? { headerHeight: 68 } : {})}
        locale="en-US"
        timeZone="UTC"
      />
    </>
  );
}
```

## Skeleton rows

Rows a remote source has not delivered yet (the unloaded blocks of
[infinite scrolling](https://salmonui.dev/docs/data-grid/infinite-scroll)) render as skeleton rows by default
(`virtualization.skeletonRows`, default `true`): one shimmering bar per visible column (up to eight), in place of
the loading text, which stays in the row for screen readers. The
row keeps `aria-busy="true"` and is
replaced by the data row when its block lands; a failed block still shows
the error and Retry, and `renderLoadingRow` wins over skeleton rows.

The shimmer is a CSS transform on a pseudo-element (no layout or paint per
frame), so scrolling over skeleton rows keeps the scroll budgets and causes
no React commits while the rendered range stays the same. It stops under
`prefers-reduced-motion: reduce` and in forced colors, where the bars stay
static. Skeleton rows are on by default; a grid with no unloaded rows renders no bars and
runs no animation, and `virtualization: { skeletonRows: false }` shows the
loading text instead. The first load of a source shows the loading indicator
instead, which has a skeleton variant too (`loadingIndicator: 'skeleton'`,
see [Data sources](https://salmonui.dev/docs/data-grid/data-sources)).

```tsx
<DataGrid data={source} columns={columns} height={400} infiniteScroll />
// The loading text instead of skeleton bars:
<DataGrid data={source} columns={columns} height={400} infiniteScroll virtualization={{ skeletonRows: false }} />
```

### Live demo: Skeleton rows

Live demo: https://salmonui.dev/demos/data-grid/skeleton-rows

50,000 remote orders read in blocks with 800 ms of latency. With virtualization.skeletonRows the unloaded rows render shimmering skeleton bars until their block lands; turned off they show the loading text. The jump buttons scroll by offset with api.scrollTo.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { createJsonDataSource } from '@salmonui/data';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridInfiniteScroll } from '@salmonui/data-grid';
import { createOrders } from '../../lib/fixtures';
import { demoFetch, type RemoteOrder } from '../../lib/remote';

const columns: DataGridColumn<RemoteOrder>[] = [
  { field: 'id', header: 'Order', primaryKey: true, width: 110 },
  { field: 'customer', header: 'Customer', width: 150 },
  { field: 'country', header: 'Country', width: 120 },
  { field: 'product', header: 'Product', width: 140 },
  { field: 'quantity', header: 'Qty', type: 'number', align: 'end', width: 80 },
  { field: 'amount', header: 'Amount', type: 'number', format: 'C2', align: 'end', width: 120 },
];

const TOTAL = 50_000;
const ROW_HEIGHT = 36;

// The first block is seeded (server render); every other block is read with 800 ms of latency.
const infiniteScroll: DataGridInfiniteScroll<RemoteOrder> = {
  initialBlocks: 1,
  initialResult: { rows: createOrders(100, 77).map(({ placed: _placed, ...row }) => row), totalRowCount: TOTAL },
};

function source() {
  return createJsonDataSource<RemoteOrder>({ url: '/api/orders?delay=800', fetch: demoFetch, key: 'id' });
}

export default function SkeletonRowsDemo() {
  const api = useRef<DataGridApi<RemoteOrder> | null>(null);
  const [skeletonRows, setSkeletonRows] = useState(true);
  // Data sources are initial-only: a new grid (key) and a new source per setting, so every jump reads again.
  const [data, setData] = useState(source);
  const toggle = (on: boolean) => {
    setSkeletonRows(on);
    setData(source());
  };
  // api.scrollTo takes the row offset in px; the grid maps it onto its compressed scroll range when needed.
  const jump = (row: number) => api.current?.scrollTo({ top: row * ROW_HEIGHT });
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={skeletonRows} onCheckedChange={(checked) => toggle(checked)}>
          Skeleton rows
        </Checkbox>
        <Button variant="outline" onClick={() => jump(20_000)}>
          Jump to row 20,000
        </Button>
        <Button variant="outline" onClick={() => jump(40_000)}>
          Jump to row 40,000
        </Button>
      </div>
      <DataGrid<RemoteOrder>
        key={skeletonRows ? 'skeleton' : 'text'}
        aria-label="50,000 remote orders with skeleton rows while blocks load"
        data={data}
        columns={columns}
        height={380}
        rowHeight={ROW_HEIGHT}
        locale="en-US"
        currency="USD"
        ref={api}
        infiniteScroll={infiniteScroll}
        virtualization={{ skeletonRows }}
      />
    </>
  );
}
```

## Server rendering

The server renders a deterministic initial range (the first `initialRows`
rows and `initialColumns` center columns, 20 each by default), independent
of the data size; the client hydrates that exact markup
and then measures the real viewport, so no hydration warning results.

## Features that work with virtualization

- Remote group expansion state is preserved across virtual scrolling
  (see Grouping).
- Aggregates and group counts cover all loaded rows, not only the visible
  ones (see Aggregates).
- Row spans work with row virtualization: a span whose first row is above
  the rendered window, however far above, is drawn from its first row with
  that row's value, so spanned and merged cells stay merged at any scroll
  position. Explicit `rowSpan` functions are found through an
  anchor index that is built once per data version as rows come into view,
  so scrolling never re-reads the rows above the window; see
  [Row and column spans](https://salmonui.dev/docs/data-grid/cell-spans).
- Cell selection works with virtualization: ranges are stored by row id and
  column id, so a Shift+click range can start in a row that is no longer
  rendered and cover tens of thousands of rows.
- Ctrl+Home and Ctrl+End (Cmd+Home and Cmd+End on macOS) move the logical
  focus to the first or last cell, then scroll it into view, under row and
  column virtualization.
- Batch editing works with row and column virtualization: drafts and
  delete marks are keyed by row id, keyboard moves scroll the next cell
  into view, and a save covers rows that are not rendered (see
  Editing).
- Pinned columns are excluded from the virtual column range: they stay
  rendered while the center columns scroll, and keyboard focus moves
  between pinned and center columns.
- Column virtualization works with every grid feature, and the column
  features act on columns outside the rendered window;
  see
  [Column virtualization compatibility](https://salmonui.dev/docs/data-grid/virtualization#column-virtualization-compatibility).

### Live demo: Spans, cell ranges and keyboard under virtualization

Live demo: https://salmonui.dev/demos/data-grid/virtual-interactions

100,000 rows by 101 columns with pinned start and end columns, a merged Block column whose row spans run through the virtualized rows, cell range selection across unrendered rows, and Ctrl+Home / Ctrl+End to unrendered corners.

`Demo.tsx`:

```tsx
'use client';

import { useRef } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridSelection } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { createWideRows, type WideRow } from '../../lib/fixtures';
import { createWideColumns } from '../../lib/wide';

const rows = createWideRows(100_000);

// 100 columns; the row number and the last column are pinned, every other column is column-virtualized.
const columns: DataGridColumn<WideRow>[] = createWideColumns(100).map((column, index, all) =>
  index === 0 ? { ...column, pinned: 'start' } : index === all.length - 1 ? { ...column, pinned: 'end' } : column,
);
// A merged "block" column: ten rows share a block, so row spans run through the virtualized rows.
columns.splice(1, 0, { id: 'block', header: 'Block', width: 100, rowSpan: true, valueGetter: (row) => `B${Math.floor(row.id / 10)}` });

const selection: DataGridSelection = { mode: 'cell', multiple: true };

export default function VirtualInteractionsDemo() {
  const api = useRef<DataGridApi<WideRow> | null>(null);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.scrollToRow('60005', { align: 'start' })}>
          Scroll to row 60,005
        </Button>
        <Button variant="outline"
          onClick={() => {
            // The serialized selection holds ranges by row id and column id, never a list of every cell.
            push(`selection: ${JSON.stringify(api.current?.getSelection()?.cellRanges ?? null)}; focused ${JSON.stringify(api.current?.getFocusedCell() ?? null)}`);
          }}
        >
          Read the selection
        </Button>
      </div>
      <DataGrid<WideRow>
        aria-label="100,000 rows by 101 columns with pinned columns, row spans and cell selection"
        data={rows}
        columns={columns}
        height={380}
        rowHeight={32}
        locale="en-US"
        selection={selection}
        ref={api}
      />
      <p className="demo-status">Click a cell, scroll far away and Shift+click another: the range spans unrendered rows. Ctrl+End (Cmd+End) jumps to the last cell; the pinned columns stay rendered while the center columns scroll.</p>
      <EventLog entries={log} />
    </>
  );
}
```

## Column virtualization compatibility

Only the visible center columns plus a small overscan are in the DOM, but
the engine addresses every column by its column id, so no feature depends on
a column being rendered. All of these work with column virtualization on:

- Grouping: the indent and the caption text stay at the start edge while
  the columns scroll (see the wide grouping demo on the
  [Grouping](https://salmonui.dev/docs/data-grid/grouping) page).
- Column spans and stacked headers: a span or a header group that starts
  before the rendered slice is still drawn; a header group spans its
  rendered leaves (stacked headers virtualize by leaf range).
- Batch editing: drafts are keyed by row id and column id, so a draft in a
  column that scrolled out of the DOM stays marked and saves.
- Row templates (`renderRow`): the template receives the rendered cells of
  the current column window.
- Detail templates and hierarchy (`renderDetail`, `childGrid`): the detail
  row spans every column, and its content, a child grid included, stays in
  view and mounted while the parent columns scroll.
- Autofill: `api.fillSelection()` and a fill handle drag that auto-scrolls
  past the right edge tile values into columns that were never rendered.

The column features work on columns outside the rendered window:

- Resize: `api.setColumnWidth()` on an unrendered column updates the scroll
  width at once, and a pointer resize works wherever the column scrolls to.
- Reorder: `api.moveColumn()`, Alt+ArrowLeft / Alt+ArrowRight on a header
  and a header drag move far columns.
- Autofit and Autofit All: widths are measured in an offscreen measurer
  from the header text and the formatted values of the rows in the rendered
  row window, read from the engine rather than from rendered cells, so a
  never-rendered column fits to the same width as a rendered one (a column
  with a `renderCell` template also reads its rendered cells).
- Print: the print projection renders every visible column and row of the
  scope without virtualization.
- Clipboard: a copied range writes every column of the range to the TSV,
  using the same display text as a rendered cell.
- Grouping from the column menu: the Group and Ungroup items work on any
  column, including one opened with `api.openColumnMenu()` while it is not
  rendered.

### Live demo: Column features under column virtualization

Live demo: https://salmonui.dev/demos/data-grid/column-virtualization

2,000 rows by 81 columns under stacked headers with column virtualization on; resize, reorder, autofit, grouping from the column menu, batch editing, the fill handle, detail rows, copy and print reach columns that were never rendered.

`Demo.tsx`:

```tsx
'use client';

import { useRef } from 'react';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridDetailContext, type DataGridSelection } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { cellHash } from '../../lib/fixtures';

// 2,000 rows by 80 editable center columns (plus the pinned #): the center zone is
// column-virtualized. Every column feature below works on columns outside the
// rendered window, because the engine addresses them by column id.
type Row = { readonly id: number } & Record<string, number | string>;

const WORDS = ['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot', 'golf', 'hotel', 'india', 'juliet'];
const COLUMN_COUNT = 80;

const rows: Row[] = [];
for (let r = 0; r < 2_000; r++) {
  const row: Record<string, number | string> = { id: r };
  for (let c = 1; c <= COLUMN_COUNT; c++) row[`c${c}`] = c % 4 === 0 ? `${WORDS[cellHash(r, c) % WORDS.length]}-${r % 97}` : cellHash(r, c) % 100_000;
  rows.push(row as Row);
}

const leaf = (c: number): DataGridColumn<Row> =>
  c % 4 === 0 ? { field: `c${c}`, header: `Text ${c}`, width: 120 } : { field: `c${c}`, header: `Value ${c}`, type: 'number', format: 'N0', align: 'end', width: 110 };

// Stacked headers: one group per ten leaves; the groups virtualize by leaf range.
const columns: DataGridColumn<Row>[] = [{ field: 'id', header: '#', primaryKey: true, width: 80, pinned: 'start', type: 'number' }];
for (let block = 0; block < COLUMN_COUNT / 10; block++) {
  columns.push({ id: `block${block + 1}`, header: `Block ${block + 1}`, columns: Array.from({ length: 10 }, (_, i) => leaf(block * 10 + i + 1)) });
}

const selection: DataGridSelection = { mode: 'cell', multiple: true, cellRange: 'box' };
const editing = { mode: 'batch' as const, fillHandle: true, confirmDiscard: false, guardUnsaved: false };
const toolbar = ['save', 'cancel', 'copy', 'print'] as const;
const renderDetail = ({ row }: DataGridDetailContext<Row>) => (
  <div style={{ padding: 12 }}>
    Row {row.id}: first column {String(row['c1'])}, last column {String(row[`c${COLUMN_COUNT}`])}. The detail row spans every column and stays in view while the columns scroll.
  </div>
);

export default function ColumnVirtualizationDemo() {
  const api = useRef<DataGridApi<Row> | null>(null);
  const [log, push] = useEventLog();
  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" onClick={() => api.current?.scrollToColumn('c75')}>
          Scroll to column 75
        </Button>
        <Button variant="outline" onClick={() => api.current?.scrollToColumn('c1')}>
          Back to the first column
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            api.current?.autoSizeColumns();
            // Column 80 was never rendered: its width comes from its values, not from the DOM.
            const width = api.current?.getState().columns?.find((c) => c.id === 'c80')?.width;
            push(`autofit all: Text 80 went from 120 px to ${width ?? 120} px`);
          }}
        >
          Autofit all columns
        </Button>
        <Button
          variant="outline"
          onClick={() => {
            api.current?.selectCellRange({ rowId: '0', field: 'c1' }, { rowId: '2', field: `c${COLUMN_COUNT}` });
            api.current?.copy();
          }}
        >
          Copy rows 0-2 over all columns
        </Button>
        <Button variant="outline" onClick={() => api.current?.openColumnMenu('c75')}>
          Column menu of column 75
        </Button>
      </div>
      <DataGrid<Row>
        aria-label="2,000 rows by 81 columns with column virtualization"
        data={rows}
        columns={columns}
        height={420}
        rowHeight={32}
        locale="en-US"
        ref={api}
        resizable
        reorderable
        columnMenu
        grouping
        selection={selection}
        editing={editing}
        toolbar={toolbar}
        renderDetail={renderDetail}
        onBeforeCopy={(e) => push(`copied ${e.rowIds.length} rows x ${e.fields.length} columns (${e.data.length} characters)`)}
        onGroupChange={(e) => push(`grouped by: ${e.groupBy.join(', ') || 'none'}`)}
        onColumnResizeEnd={(e) => push(`resized ${e.field} to ${e.width} px`)}
        onColumnDrop={(e) => push(`moved ${e.field} to index ${e.toIndex}`)}
      />
      <p className="demo-status">Scroll sideways: only the visible columns render, yet autofit, copy, print, grouping and the fill handle cover all 80 columns.</p>
      <EventLog entries={log} />
    </>
  );
}
```

## API reference

See [`DataGridVirtualization`](https://salmonui.dev/docs/reference/data-grid/DataGridVirtualization)
and the sizing props (`height`, `rowHeight`, `estimatedRowHeight`,
`getRowHeight`, `initialRows`, `initialColumns`) on
[`DataGridProps`](https://salmonui.dev/docs/reference/data-grid/DataGridProps).
