# Show a million rows

> Render, sort and scroll one million client-side rows with row and column virtualization, and the habits that keep a large grid fast.

Birch UI Grid only creates DOM for the rows and columns in view, so a million rows scroll as smoothly as a hundred. What does cost time is the work you put around the grid: building the array, value getters and renderers. This recipe loads 1,000,000 trades and keeps that work small.

**Live demo: One million rows** (runs on the HTML version of this page). Source of `demos/recipe-grid-million-rows.ts`. Imports from `./_shared` and `./_scheduler-data` are sample data and small UI helpers used only by the docs.

```ts
import { createGrid, type ColumnDef } from '@birchui/core';
import { button, currency, docsTheme, layout, onDocsThemeChange } from './_shared';

export const meta = { title: 'One million rows', height: 460 };

const ROW_COUNT = 1_000_000;

interface Trade {
  id: number;
  account: string;
  symbol: string;
  side: 'Buy' | 'Sell';
  quantity: number;
  price: number;
}

const ACCOUNTS = ['Northwind Pension', 'Kestrel Capital', 'Harbourline Trust', 'Andes Holdings', 'Cedar & Stone'];
const SYMBOLS = ['ACME', 'GLOBX', 'INIT', 'NWND', 'KSTR', 'HRBR', 'SKRA', 'LOTS'];

function makeTrades(count: number): Trade[] {
  const trades: Trade[] = new Array(count);
  for (let i = 0; i < count; i++) {
    trades[i] = {
      id: i + 1,
      account: ACCOUNTS[i % ACCOUNTS.length],
      symbol: SYMBOLS[(i * 7) % SYMBOLS.length],
      side: i % 3 === 0 ? 'Sell' : 'Buy',
      quantity: 10 + ((i * 37) % 990),
      price: 20 + ((i * 7919) % 18000) / 100,
    };
  }
  return trades;
}

const columns: ColumnDef<Trade>[] = [
  { field: 'id', header: 'Trade', type: 'number', width: 110 },
  { field: 'account', header: 'Account', width: 200 },
  { field: 'symbol', header: 'Symbol', width: 100 },
  { field: 'side', header: 'Side', width: 90 },
  { field: 'quantity', header: 'Quantity', type: 'number', width: 110 },
  { field: 'price', header: 'Price', type: 'number', width: 110, format: (value) => currency.format(Number(value)) },
];

export default function mount(el: HTMLElement): () => void {
  const { toolbar, body, status } = layout(el);
  const started = performance.now();
  const grid = createGrid<Trade>(body, {
    columns,
    rows: makeTrades(ROW_COUNT),
    getRowId: (trade) => String(trade.id),
    theme: docsTheme(),
    ariaLabel: 'One million trades',
  });
  status.textContent = `${ROW_COUNT.toLocaleString('en-US')} rows ready in ${Math.round(performance.now() - started)} ms.`;
  toolbar.append(
    button('Jump to row 500,000', () => grid.scrollToRow(499_999, 'center')),
    button('Last row', () => grid.scrollToRow(ROW_COUNT - 1, 'end')),
    button('Sort by quantity', () => {
      const t = performance.now();
      grid.setSort([{ colId: 'quantity', dir: 'desc' }]);
      status.textContent = `Sorted in ${Math.round(performance.now() - t)} ms.`;
    }),
  );
  const offScroll = grid.on('viewportScroll', () => {
    status.textContent = `Rows in the DOM: ${grid.getRenderedRows().length} of ${ROW_COUNT.toLocaleString('en-US')}.`;
  });
  const stopTheme = onDocsThemeChange((theme) => grid.update({ theme }));
  return () => {
    offScroll();
    stopTheme();
    grid.destroy();
  };
}
```

## 1. Build compact rows

```ts title="trades.ts"
export interface Trade {
  id: number;
  account: string;
  symbol: string;
  side: 'Buy' | 'Sell';
  quantity: number;
  price: number;
}

export function decodeTrades(buffer: ArrayBuffer, accounts: string[], symbols: string[]): Trade[] {
  const view = new DataView(buffer);
  const count = view.byteLength / 16;
  const trades: Trade[] = new Array(count);
  for (let i = 0; i < count; i++) {
    const offset = i * 16;
    trades[i] = {
      id: view.getUint32(offset),
      account: accounts[view.getUint16(offset + 4)],
      symbol: symbols[view.getUint16(offset + 6)],
      side: view.getUint8(offset + 8) === 1 ? 'Sell' : 'Buy',
      quantity: view.getUint16(offset + 10),
      price: view.getFloat32(offset + 12),
    };
  }
  return trades;
}
```

Flat objects with primitive fields sort and filter fastest. Precompute derived values such as `notional = quantity * price` while decoding instead of in a `valueGetter`. For very large payloads, decode in a Web Worker and post the array back.

## 2. Create the grid

```ts title="trades-grid.ts"
import { createGrid, type ColumnDef } from '@birchui/core';
import type { Trade } from './trades';

const usd = new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' });

const columns: ColumnDef<Trade>[] = [
  { field: 'id', header: 'Trade', type: 'number', width: 110 },
  { field: 'account', header: 'Account', width: 200, filter: 'set' },
  { field: 'symbol', header: 'Symbol', width: 100, filter: 'set' },
  { field: 'side', header: 'Side', width: 90 },
  { field: 'quantity', header: 'Quantity', type: 'number', width: 110 },
  { field: 'price', header: 'Price', type: 'number', width: 110, format: (value) => usd.format(Number(value)) },
];

export function mountTrades(container: HTMLElement, trades: Trade[]) {
  return createGrid<Trade>(container, {
    columns,
    rows: trades,
    getRowId: (trade) => String(trade.id),
    rowHeight: 32,
    ariaLabel: 'Trades',
  });
}
```

Give the container a fixed height, or a height from its layout such as `flex: 1` inside a sized parent. A grid in a container without height renders no rows.

## 3. Update in place

Replace rows only when the whole data set changes. For corrections and new trades, use a transaction:

```ts
grid.applyTransaction({ add: newTrades, update: correctedTrades, remove: cancelledIds });
```

## How it works

- Row virtualization renders the visible rows plus `overscanRows` on each side. Column virtualization does the same horizontally with `overscanColumns`.
- Browsers limit element height to a few million pixels. The grid scales its scroll range above that limit, so the last of a million 32 px rows stays reachable.
- Numeric, date and boolean columns without a custom `comparator` use a faster sort path than text columns.

## Pitfalls

- **Debounce the quick filter.** The first quick filter on a million rows builds a search string per row. Wait 150 ms after typing before calling `setQuickFilter()`.
- **Keep `format` and `cell` cheap.** They run for every cell that scrolls into view. Create `Intl` formatters once, as above.
- **Do not call `setRows()` per tick.** It re-indexes every row. See [Streaming live updates](https://docs.birchui.com/recipes/grid-live-updates.md).
- **Consider the server.** If a million rows is only the first page of what exists, use the [server-side row model](https://docs.birchui.com/recipes/grid-server-side-rest.md) instead of shipping everything to the browser.

## Related

- [Virtualization](https://docs.birchui.com/grid/virtualization.md), including [Guidance for a million rows](https://docs.birchui.com/grid/virtualization.md#guidance-for-a-million-rows) and [reference timings](https://docs.birchui.com/grid/virtualization.md#reference-timings).
- [Updating data](https://docs.birchui.com/grid/updating-data.md).
