# Lazy load grouping

> Server-side grouping that loads group captions first and children on demand.

Canonical: https://salmonui.dev/docs/data-grid/lazy-grouping

With lazy grouping (`grouping.lazy`) and a remote source that declares
`capabilities.lazyGroups`, grouping runs on the server. The first response holds only the top-level
group captions with their counts; a group's children (sub-groups or rows)
are requested when it expands, in chunks. Group captions carry
aggregates computed by the server. Groups start collapsed
in lazy mode (`grouping.defaultExpanded` defaults to `false` there).

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

<DataGrid
  data={orders}
  columns={columns}
  grouping={{ lazy: true, lazyChunkSize: 50, groupBy: ['country', 'customer'] }}
  onGroupToggle={(event) => console.log(event.path, event.expanded, event.lazy)}
/>
```

Each group tracks its own load state, so a slow or failed group shows its
own loading indicator or retry action without blocking the rest of the grid.
A sort or filter change invalidates loaded children: the root
reloads, groups that were expanded stay expanded and reload their children.
The expand and collapse events `onBeforeGroupToggle` /
`onGroupToggle` carry `lazy: true` in lazy mode.

A group with more children than one chunk (`grouping.lazyChunkSize`,
default 100) shows a Load more button on its caption; each click appends
the next chunk. The data source reports whether more children
exist: `createJsonDataSource` sets `pageInfo.hasNextPage` from the
server's `next` cursor, or for offset ranges from `total`, which the
reference handler returns with every group level and child page.

With `infiniteScroll` on as well, scrolling appends the chunks: when the last loaded row of an expanded group with more children
comes within `infiniteScroll.threshold` rows (default half a block, 50
rows) below the rendered rows, the grid requests that group's next chunk.
Nested groups append their sub-groups the same way. The Load more button
stays on the caption as the keyboard and screen reader path. The check
runs only when the rendered row window or the row model changes, never
per scroll frame. Top-level captions arrive in one root read (or one page
of them with `paging`), so there is no caption page to append.

With `paging`, the pager pages the top-level groups: the root request carries the group path `[]`
and the page (`{ offset, limit }` over the groups) in one request, the
pager's total is the number of top-level groups, and a page change loads
that page's captions. Children of a group on the page page by their own
chunks, not by the grid page. Expanded groups stay expanded across pages.

The demo's endpoint runs the reference protocol handler (behind a Next.js
route handler, or in the browser on the static site); any backend that speaks the protocol works the same way.

### Live demo: Lazy load grouping

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

Two-level grouping over 50,000 remote orders. The server returns group captions with their aggregates first; children load in chunks of 50 when a group expands, with a per-group loading state and a Load more button for the next chunk; with infinite scrolling on, scrolling near the end of a group's loaded rows appends the next chunk; paging pages the countries in the root request; a filter change reloads loaded groups and keeps expansion.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { createJsonDataSource } from '@salmonui/data';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { DataGrid, type DataGridAggregateRow, type DataGridApi, type DataGridColumn } from '@salmonui/data-grid';
import { EventLog, useEventLog } from '../../components/demo-kit';
import { demoFetch, type RemoteOrder } from '../../lib/remote';

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

// Caption aggregates are computed by the server and arrive with the group captions.
const aggregates: DataGridAggregateRow<RemoteOrder>[] = [
  { columns: [{ field: 'amount', type: 'sum', format: 'C0', renderGroupCaption: ({ formatted }) => <span>Σ {formatted['sum']}</span> }] },
];

// Initial grouping; a constant (the options prop is reactive).
const grouping = { groupBy: ['country', 'city'], lazy: true, lazyChunkSize: 50 };
// with paging, each root request pages the top-level groups.
const paging = { pageSize: 3 };
// with infiniteScroll, scrolling near the end of a group's
// loaded rows appends its next chunk (Load more stays for the keyboard).
const infiniteScroll = { threshold: 10 };

export default function LazyGroupingDemo() {
  const api = useRef<DataGridApi<RemoteOrder> | null>(null);
  const [log, push] = useEventLog();
  const [bigOnly, setBigOnly] = useState(false);
  const [paged, setPaged] = useState(false);
  const [onScroll, setOnScroll] = useState(false);
  const [source] = useState(() =>
    createJsonDataSource<RemoteOrder>({
      url: '/api/orders?delay=300',
      fetch: demoFetch,
      key: 'id',
      // The group requests: group path and page travel in one request.
      onRequest: (event) => {
        const wire = event.request as { groupPath?: { key: unknown }[]; query?: { page?: unknown } };
        if (wire.groupPath) push(`group [${wire.groupPath.map((s) => String(s.key)).join(' / ')}] page ${JSON.stringify(wire.query?.page ?? null)}`);
      },
      onResponse: (event) => push(`${event.kind}: ${Math.round(event.durationMs)} ms`),
    }),
  );
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox
          checked={bigOnly}
          onCheckedChange={(checked) => {
            setBigOnly(checked);
            if (checked) api.current?.filterColumn('amount', 'greaterThan', 500);
            else api.current?.clearFiltering();
          }}
        >
          Amount &gt; 500 (reloads loaded groups)
        </Checkbox>
        <Checkbox
          checked={paged}
          onCheckedChange={(checked) => {
            setPaged(checked);
            setOnScroll(false);
            setBigOnly(false);
          }}
        >
          Page the countries (3 per page)
        </Checkbox>
        <Checkbox
          checked={onScroll}
          onCheckedChange={(checked) => {
            setOnScroll(checked);
            setPaged(false);
            setBigOnly(false);
          }}
        >
          Load more on scroll (infiniteScroll)
        </Checkbox>
      </div>
      {/* Paging and infinite scroll are modules chosen at mount, so switching them remounts the grid (key). */}
      <DataGrid<RemoteOrder>
        key={paged ? 'paged' : onScroll ? 'infinite' : 'scrolling'}
        aria-label="Lazily loaded order groups"
        data={source}
        columns={columns}
        sorting
        filtering
        height={400}
        locale="en-US"
        currency="USD"
        ref={api}
        aggregates={aggregates}
        grouping={grouping}
        {...(paged ? { paging } : {})}
        {...(onScroll ? { infiniteScroll } : {})}
        onGroupToggle={(event) => push(`${event.expanded ? 'expand' : 'collapse'} ${event.path.map((p) => String(p.key)).join(' / ')} (lazy: ${event.lazy})`)}
      />
      <EventLog entries={log} label="Requests and group events" />
    </>
  );
}
```

## API reference

See [`DataGridGrouping`](https://salmonui.dev/docs/reference/data-grid/DataGridGrouping)
(`lazy`, `lazyChunkSize`, `defaultExpanded`) and
[`DataGridGroupToggleEvent`](https://salmonui.dev/docs/reference/data-grid/DataGridGroupToggleEvent)
in the API reference.
