Load rows while scrolling
Fetch rows in blocks as the user scrolls, so a grid shows a large server result without loading all of it first.
Scroll mode fetches the rows the user scrolls into. The grid shows one continuous list. useDataGridServerRows calls your fetchRows function once for each block of rows that is not loaded yet.
pnpm dlx shadcn@latest add @gridcn/data-grid-server
Use scroll mode for one continuous result. Scroll mode and pagination on one grid are not supported. For numbered pages, see Load rows by page. The hook cannot switch mode after mount. See Troubleshoot server data.
Fetch blocks
- Call
useDataGridServerRowswithmode: "scroll"andfetchRows. - Resolve
fetchRowswith the rows[start, end)and the row count of the whole result. - Spread
server.gridPropsontoDataGrid.
This grid loads orders from an API:
"use client";
import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import {
useDataGridServerRows,
} from "@/components/data-grid-server/data-grid-server";
type Order = { id: string; customer: string; total: number };
const columns = defineColumns<Order>()([
{ id: "customer", header: "Customer", accessorKey: "customer" },
{ id: "total", header: "Total", accessorKey: "total", type: "number" },
]);
export function OrdersGrid() {
const server = useDataGridServerRows<Order>({
mode: "scroll",
fetchRows: async ({ start, end, signal }) => {
const query = new URLSearchParams({
offset: String(start),
limit: String(end - start),
});
const response = await fetch(`/api/orders?${query}`, { signal });
const answer = await response.json();
return { rows: answer.rows, totalRowCount: answer.total };
},
});
return <DataGrid {...server.gridProps} columns={columns} className="h-96" />;
}The hook reads the row count from the first answer, so the grid needs no separate endpoint for the row count.
How blocks load
The first request is always block 0, the rows [0, blockSize). The first answer picks the fetch order. An answer with totalRowCount and no nextCursor gives random access: the hook knows the row count, so it can fetch any block in any order. This page describes random access. Other answers give a sequential source. See Load without row count.
- The hook sizes
datato the row count. Every row without data renders as a skeleton row. - When the rendered rows move, the hook adds
overscanrows on each side and rounds the span out toblockSizerows. This span is the wanted range. It requests each missing block with one request. - A block request starts after the block stays in the wanted range for
loadDelayMsmilliseconds (default 100). A fast scroll starts no request until it rests. Block 0,refresh(),retry(), and the refetch after the first answer or a count change start at once. PassloadDelayMs: 0to start at once. - A request aborts when its rows leave the keep range, which is the wanted range plus one block on each side. At most
maxConcurrentFetchesrequests run at once (default 3, at most 16). The blocks ofrefresh()andretry()wait in a queue behind that cap and count asloading. - A scroll never requests a loaded or in-flight block again. Loaded blocks load again after
refresh(), after a row operation, and after a changed row count. Adjacent loaded blocks merge. - A request holds
spec,start,end,cursor, andsignal.cursorisundefinedin random access. - A spec change, a changed row count, or a
refresh()replaces the requests in flight and aborts theirsignal, as an unmount does. A spec change or a changedtotalRowCountdrops the loaded rows. - A short answer marks only its rows as loaded and warns in development. The next report of the rendered rows requests the rest.
blockSize is 50 and overscan is 30 by default. Pass source: "random" to force random access. A scroll-mode grid defaults sortMode and filterMode to "server": see Query server rows.
Skeleton rows
data is a sparse array with the length of the row count. Loaded indices hold rows. Unloaded indices are holes, and each hole renders skeleton cells with a data-skeleton attribute. To restyle them with CSS, see Style contract.
- The function forms of column
readOnly,getRowClassName,getCellClassName, and columncellClassNameskip holes. They never receive anundefinedrow. getRowIdruns on loaded rows only. A hole gets a placeholder id that names a position and not a record.isPlaceholderRowId(id)fromdata-gridtells a placeholder id from a real id, andapi.getViewRowIds({ loaded: true })lists the loaded rows only.- A skeleton cell opens no editor, and the grid skips a write to an unloaded row.
deleteRows,deleteRowsAt,duplicateRows,duplicateRowsAt,insertRow, andinsertRowsdo nothing when their target touches an unloaded row, and warn once per grid in development.reorderRowsandmoveRowsBydo nothing while any row is unloaded. Delete known rows withdeleteRows. See Change server rows.
Edit loaded rows
gridProps.onDataChange merges each edit, insert, and delete into the loaded rows. Put your own handler in the onDataChange option of the hook, or in an onDataChange prop after the spread. Both run next to the merge. Send changes to your backend from onSave.
When the block of an unsaved row loads again, the answer replaces the unsaved value. See Tune row retention.
Show the request state
server.rootProps carries loading, error, and onRetry. loading is true while a block request runs. Before the first block lands, the grid has no rows and fills the body with skeleton rows. Once rows exist, the root shows a slim progress bar under the header, and the unloaded rows keep their skeleton cells.
For a composed layout, spread server.providerProps onto DataGridProvider and server.rootProps onto DataGridRoot. server.gridProps is both parts together.
See Row limits for the browser height limit.
Start from a first answer
Pass the answer of block 0 as initialAnswer, for example from a Server Component. The server HTML then holds the rows, and the hook sends no request for block 0. The first-answer rule of fetchRows picks the source.
A grouped spec takes the top-level groups. Rows past blockSize are cut. Another first spec drops the answer. onLoaded does not fire for it.
Related
- Select server rows: select all matching
- Server rows options: every option and result field
- Recover from load errors: a block that fails
- Tune row retention: refresh and evict loaded rows
- Query server rows: sort, filter, and search on the server