# Infinite scrolling

> Remote rows read in blocks as the viewport approaches them, with loading rows, a bounded block cache, a load-next command and server-rendered first blocks.

Canonical: https://salmonui.dev/docs/data-grid/infinite-scroll

`infiniteScroll` turns on infinite scrolling for a remote data source.
The grid reads rows in
blocks with `DataSourceRequest.range`: the first read covers
`initialBlocks` blocks, and later reads follow the viewport as it
approaches rows that are not loaded. `true` uses the defaults; an object
sets them.

```tsx
const source = createJsonDataSource<Order>({ url: '/api/orders', key: 'id' });

<DataGrid data={source} columns={columns} height={400} infiniteScroll={{ cache: true, maxBlocks: 6 }} />
```

| Option | Default | Meaning |
| --- | --- | --- |
| `infiniteScroll` | off | `true` or a settings object |
| `initialBlocks` | 3 | Blocks of the first read |
| `maxBlocks` | 3 | Blocks kept in memory with `cache` |
| `cache` | false | Bound the blocks in memory |
| `blockSize` | 100 | Rows per block and per read unit |
| `threshold` | half a block | Prefetch distance in rows |
| `debounce` | 50 ms | Quiet time before a jump target is read |
| `initialResult` | — | Seeded first blocks (server rendering) |

Without `cache` every loaded block is kept. With
`cache: true` at most `maxBlocks` blocks stay in memory (never fewer than
the viewport needs): the block farthest from the viewport is evicted and
read again when the viewport returns. The bound is a performance gate:
with `cache` and `maxBlocks: 3`, scrolling through 1,000,000
rows holds at most 400 rows and grows the heap by less than 4 MB
(see
[performance](https://salmonui.dev/docs/data-grid/performance)). The demo below sets `maxBlocks: 6`,
and its status line shows the rows in memory and the evicted blocks. The
rendered DOM rows are bounded separately by virtualization. A scrollbar
drag or jump issues one read once the viewport is still; reads for
blocks scrolled past are aborted.

The data source keeps its default offset paging; the grid manages the
blocks. Remote reads themselves are covered on the
[data sources](https://salmonui.dev/docs/data-grid/data-sources) page.

### Live demo: Infinite scrolling

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

50,000 remote orders read in blocks of 100 as the viewport approaches unloaded rows. The first 300 rows are seeded with initialResult and render on the server; unloaded rows show loading rows; with cache and maxBlocks 6 the farthest blocks are evicted; sorting resets to the top; a button loads the next block; another adds an order at the bottom, which lands after the last row.

`Demo.tsx`:

```tsx
'use client';

import { useEffect, useRef, useState } from 'react';
import { createJsonDataSource } from '@salmonui/data';
import type { DataSourceEvent, DataSourceRequest, DataSourceResult, WriteRequest, WriteResult } from '@salmonui/core/data';
import type { DataSource } from '@salmonui/data-grid/engine';
import { Button } from '@salmonui/buttons/button';
import { DataGrid, type DataGridApi, type DataGridColumn, type DataGridEditing, type DataGridInfiniteScroll } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
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;

// The first three blocks (rows [0, 300)), seeded so they render on the server
// and are not requested again. `createOrders` draws from one seeded sequence
// row by row, so its first 300 rows equal the first 300 of the endpoint's
// 50,000 (lib/orders-server.ts uses the same seed).
const infiniteScroll: DataGridInfiniteScroll<RemoteOrder> = {
  cache: true,
  maxBlocks: 6,
  initialResult: {
    rows: createOrders(300, 77).map(({ placed: _placed, ...row }) => row),
    totalRowCount: TOTAL,
  },
};

// Adding only: added rows open at the bottom edge and save through `write()`.
const editing: DataGridEditing<RemoteOrder> = { newRowPosition: 'bottom', edit: false, delete: false };

const INITIAL_STATUS = `300 of ${TOTAL.toLocaleString('en-US')} rows in memory · 0 requests · 0 aborted · 0 evicted`;

/**
 * The orders endpoint is read-only and shared by every visitor, so this
 * source keeps the rows added in this page in the browser and serves them
 * after the server's 50,000 rows, as a server that appends new rows would
 * (in every sort order: they are the newest orders). Reads below row 50,000
 * go to the endpoint.
 */
function withAppendedRows(server: DataSource<RemoteOrder>): DataSource<RemoteOrder> {
  const appended: RemoteOrder[] = [];
  const listeners = new Set<(event: DataSourceEvent<RemoteOrder>) => void>();
  return {
    mode: 'remote',
    capabilities: { ...server.capabilities, write: true },
    async read(request: DataSourceRequest): Promise<DataSourceResult<RemoteOrder>> {
      const range = request.range;
      const total = TOTAL + appended.length;
      if (!range || range.end <= TOTAL) {
        const result = (await server.read(request)) as DataSourceResult<RemoteOrder>;
        return appended.length ? { ...result, totalRowCount: total, pageInfo: { hasNextPage: true } } : result;
      }
      const local = appended.slice(Math.max(0, range.start - TOTAL), range.end - TOTAL);
      if (range.start >= TOTAL) return { version: request.version, rows: local, totalRowCount: total, performed: ['search', 'filter', 'sort', 'page'], pageInfo: { hasNextPage: false } };
      const result = (await server.read({ ...request, range: { start: range.start, end: TOTAL } })) as DataSourceResult<RemoteOrder>;
      return { ...result, rows: [...result.rows, ...local], totalRowCount: total, pageInfo: { hasNextPage: range.end < total } };
    },
    async write(request: WriteRequest<RemoteOrder>): Promise<WriteResult<RemoteOrder>> {
      const added = request.added.map((a) => ({ tempId: a.tempId, row: a.row }));
      for (const a of added) appended.push(a.row);
      // A structural write echo: the grid re-reads the blocks around the viewport.
      const event: DataSourceEvent<RemoteOrder> = { type: 'patch', rows: added.map((a) => a.row), updated: [], added: added.map((a) => a.row.id), removed: [] };
      for (const listener of listeners) listener(event);
      return { version: request.version, status: 'applied', added, changed: [], deleted: [] };
    },
    subscribe(listener) {
      listeners.add(listener);
      const off = server.subscribe?.(listener);
      return () => {
        listeners.delete(listener);
        off?.();
      };
    },
  };
}

function describe(api: DataGridApi<RemoteOrder>): string {
  // Typed façade: present because the grid has `infiniteScroll`.
  const facade = api.engine.infiniteScroll;
  const stats = facade?.getStats();
  if (!facade || !stats) return INITIAL_STATUS;
  const status = facade.getStatus();
  const total = status.totalRowCount ?? TOTAL;
  return `${status.loadedRowCount.toLocaleString('en-US')} of ${total.toLocaleString('en-US')} rows in memory · ${stats.requests} requests · ${stats.aborted} aborted · ${stats.evicted} evicted`;
}

export default function InfiniteScrollDemo() {
  const api = useRef<DataGridApi<RemoteOrder> | null>(null);
  const [log, push] = useEventLog();
  const [status, setStatus] = useState(INITIAL_STATUS);
  // Created once per mounted grid (data sources are initial-only). Default
  // offset paging: the grid's infinite scroll module manages the blocks.
  const [source] = useState(() =>
    withAppendedRows(createJsonDataSource<RemoteOrder>({
      url: '/api/orders?delay=150',
      fetch: demoFetch,
      key: 'id',
      onResponse: (event) => {
        const query = 'query' in event.request ? event.request.query : undefined;
        const page = query?.page && 'offset' in query.page ? `rows [${query.page.offset}, ${query.page.offset + query.page.limit})` : 'rows';
        const sort = query?.sort?.length ? ` sorted by ${query.sort.map((s) => `${s.field} ${s.dir}`).join(', ')}` : '';
        push(`${event.kind} ${page}${sort}: ${Math.round(event.durationMs)} ms`);
      },
    })),
  );
  const added = useRef(0);

  // scroll to the last row, then open a new row at the bottom edge
  // (Enter or Save writes it; it lands after the last row).
  const addOrder = () => {
    const grid = api.current;
    if (!grid) return;
    const count = grid.engine.infiniteScroll?.getStatus().totalRowCount ?? TOTAL;
    const last = grid.engine.getRowIdAt(count - 1);
    if (last !== undefined) grid.scrollToRow(last, { align: 'end' });
    added.current += 1;
    grid.addRow({ id: `NEW-${added.current}`, customer: 'New customer', country: 'Germany', product: 'Chai', quantity: 1, amount: 18 });
  };

  // Re-read on every engine change and after every logged response (the
  // request counters change without a snapshot change).
  useEffect(() => {
    const grid = api.current;
    if (!grid) return;
    const update = () => setStatus(describe(grid));
    update();
    return grid.engine.subscribe(update);
  }, [log]);

  return (
    <>
      <div className="demo-toolbar">
        <Button variant="outline" type="button" onClick={() => api.current?.engine.infiniteScroll?.loadNext()}>
          Load next block
        </Button>
        <Button variant="outline" type="button" onClick={addOrder}>
          Add order at the bottom
        </Button>
      </div>
      <DataGrid<RemoteOrder>
        aria-label="50,000 remote orders with infinite scrolling"
        data={source}
        columns={columns}
        sorting
        height={380}
        locale="en-US"
        currency="USD"
        ref={api}
        editing={editing}
        infiniteScroll={infiniteScroll}
      />
      <p className="demo-status" aria-live="polite" data-testid="infinite-status">
        {status}
      </p>
      <EventLog entries={log} label="Requests" />
    </>
  );
}
```

## Known and unknown totals

When the server reports `totalRowCount`, the scroll range covers every row
from the start, and rows that are not loaded yet render as loading rows.
Without a total the grid grows as blocks arrive, with one loading row at
the end while more rows may follow.

## Loading rows

A loading row has the `.salmon-data-grid-loading-row` class, `aria-busy` and
`data-status="loading"`; after a failed read it switches to
`data-status="error"` with a Retry button. `renderLoadingRow`
replaces its content and receives `{ rowIndex, status, error, retry }`.
Without it, a loading row draws shimmering skeleton bars by default
([skeleton rows](https://salmonui.dev/docs/data-grid/virtualization), `virtualization.skeletonRows`);
`virtualization: { skeletonRows: false }` shows the loading text instead.

```tsx
<DataGrid
  data={source}
  columns={columns}
  infiniteScroll
  renderLoadingRow={({ status, retry }) => (status === 'error' ? <button onClick={retry}>Try again</button> : 'Loading orders…')}
/>
```

## Sorting, filtering and search

A sort, filter or search change drops the loaded blocks, scrolls back to
the top and reads the first blocks of the new query.

## Grouping

With grouping, infinite scroll yields to group loading: group captions
load first and their children load on demand, in chunks. With
lazy grouping (`grouping.lazy`), scrolling near the end of an expanded
group's loaded rows appends its next chunk, so a long group scrolls like
an infinite list; `threshold` sets how many rows ahead the next
chunk is requested, and the caption's Load more button remains the
keyboard path. See [lazy grouping](https://salmonui.dev/docs/data-grid/lazy-grouping) and its demo with
"Load more on scroll" checked.

## Editing and keyboard

Loaded rows can be selected and edited like any other rows; the data
source's write echoes update the loaded blocks in place, and added or
removed rows re-read the visible blocks. ArrowDown or Ctrl+End
onto a row that is not loaded yet loads its block first and then
focuses it.

### Adding rows at the bottom

With `editing.newRowPosition: 'bottom'`, `addRow()` (or Insert, or the
toolbar's Add) opens the new row in a band pinned to the bottom edge of
the body, wherever the viewport is; the row is not part of the loaded
blocks until the data source stores it.

```tsx
<DataGrid
  data={source}
  columns={columns}
  infiniteScroll
  editing={{ newRowPosition: 'bottom' }}
  ref={api}
/>;

api.current?.addRow({ customer: 'New customer' }); // Enter or api.save() writes it
```

Saving calls the source's `write()`. Its echo (a `patch` event with
`added`) is a structural write: the grid re-reads the blocks around the
viewport and keeps rendering them until the re-read lands, so nothing
blinks. The re-read requests whole blocks, so a row the server appended
past the old end is read with them, and the row count follows the new
`totalRowCount`. Without a total the end the grid found by reading is
dropped and found again, so appended rows are read when the viewport
reaches the end. Where the row lands is the server's choice (with a sort,
its sorted position); the demo appends it after the last row.

## Load next block

`infiniteScroll.loadNext` reads the block after the last loaded row.
`infiniteScroll.retry` repeats a failed read,
and `infiniteScroll.reload` re-reads from the start. The engine reports the
load state through `api.engine.infiniteScroll.getStatus()` (`status`,
`totalRowCount`, `loadedRowCount`, `hasMore`, ...) and request counters
through `getStats()` (`requests`, `aborted`, `evicted`).

`api.engine.infiniteScroll` is typed (`DataGridInfiniteScrollFacade`): it is
present when the grid has `infiniteScroll`, and its `loadNext()`,
`retry()` and `reload()` dispatch the commands above. Until the infinite
scroll code has loaded (right after mount), the commands are rejected with
`moduleLoading` and `getStats()` returns `undefined`.

```ts
api.engine.infiniteScroll?.loadNext();
// or
api.engine.dispatch({ type: 'infiniteScroll.loadNext' });
```

For "load next set" buttons instead of scroll-triggered loading, call
`loadNext` from your button.

## Server rendering

`initialResult: { rows, totalRowCount?, hasNextPage? }` seeds the first
blocks, for example with rows a server component fetched. They render on
the server and on the first client render, and are not requested again.
Rows start at row 0. The demo seeds its first 300 rows this way.

## Memory and the DOM

- Rows are always DOM-virtualized, so `cache` and `maxBlocks` bound the row
  data held in memory, not the rendered DOM rows; the DOM holds the visible
  rows plus overscan either way (rendered rows never accumulate,
  while the memory that grows with infinite scrolling is row data). With `infiniteScroll={{ cache: true, maxBlocks }}`,
  scrolling back to an evicted block shows a short loading row while the
  block is read again.
- With a local array, `infiniteScroll` has no effect: every row is already
  present and virtualized.

## API reference

See [`DataGridInfiniteScroll`](https://salmonui.dev/docs/reference/data-grid/DataGridInfiniteScroll)
and [`DataGridLoadingRowContext`](https://salmonui.dev/docs/reference/data-grid/DataGridLoadingRowContext)
in the API reference.
