gridcn2.0.0
Server and data examples

Scroll mode example

Load rows from a simulated server in blocks while the user scrolls, with a plain fetcher or a TanStack Query or SWR cache.

In scroll mode, useDataGridServerRows owns the sparse row array and the block bookkeeping. The first grid has 100,000 rows. The hook fetches the blocks of the rendered rows plus overscan, and skeleton rows hold the space until each block lands.

100,000 / 100,000 rows loaded · fetching… · cap 2,000 · requests started 0, aborted 0
ID
Name
Email
Score
pnpm dlx shadcn@latest add @gridcn/data-grid-lazy-demo

The status line shows the loaded rows, the 2,000-row cap (maxLoadedRows), and the requests started and aborted. The buttons try the failure paths. A permanent failure lasts until you press Fix backend. Evict loaded rows removes every loaded row until it scrolls into view again.

Write the fetcher

fetchRows resolves the rows [start, end) and the row count of the whole result:

import { DataGrid, defineColumns } from "@/components/data-grid/data-grid";
import {
  useDataGridServerRows,
} from "@/components/data-grid-server/data-grid-server";

type Person = { id: string; name: string };

const columns = defineColumns<Person>()([
  { id: "name", header: "Name", accessorKey: "name" },
]);

export function PeopleGrid() {
  const server = useDataGridServerRows<Person>({
    mode: "scroll",
    fetchRows: async ({ start, end, signal }) => {
      const query = `offset=${start}&limit=${end - start}`;
      const response = await fetch(`/api/people?${query}`, { signal });
      const answer = await response.json();
      return { rows: answer.rows, totalRowCount: answer.total };
    },
  });

  return <DataGrid {...server.gridProps} columns={columns} className="h-96" />;
}
  • signal aborts the request when the block scrolls out of range, the spec or row count changes, evict covers it, or the grid unmounts. An aborted request is no error.
  • A failed block stays unloaded, and onError fires. The block loads again the next time it scrolls into view. The error bar offers Retry, and server.retry() repeats the failed blocks.

Cache the blocks with TanStack Query

Call queryClient.fetchQuery inside fetchRows and use the block as the query key. With staleTime: Infinity, a cached block never goes stale. Nothing observes a block, so TanStack Query drops it after gcTime, which is 5 minutes by default. Set gcTime: Infinity to keep each block for the session. The demo has no sort, so its key holds only the range.

10,000 / 10,000 rows loaded · fetching…0 windows in the query cache
ID
Name
Email
Score
pnpm dlx shadcn@latest add @gridcn/data-grid-lazy-react-query-demo

If the user can sort or filter, send the spec and put serverSpecKey(spec) in the key:

import { useQueryClient } from "@tanstack/react-query";
import { serverSpecKey } from "@/components/data-grid/data-grid";
import {
  useDataGridServerRows,
} from "@/components/data-grid-server/data-grid-server";

type Person = { id: string; name: string };
type Block = { rows: Person[]; totalRowCount: number };

export function useCachedPeople() {
  const queryClient = useQueryClient();
  return useDataGridServerRows<Person>({
    mode: "scroll",
    fetchRows: ({ spec, start, end }) =>
      queryClient.fetchQuery({
        queryKey: ["people", serverSpecKey(spec), start, end],
        staleTime: Infinity,
        gcTime: Infinity,
        queryFn: async ({ signal }): Promise<Block> => {
          const body = JSON.stringify({ spec, start, end });
          const init = { method: "POST", body, signal };
          const response = await fetch("/api/people", init);
          const answer = await response.json();
          return { rows: answer.rows, totalRowCount: answer.total };
        },
      }),
  });
}

queryFn passes the signal of TanStack Query to the fetch, not the request signal. If the hook aborts the request, the fetch runs on and fills the cache.

Cache the blocks with SWR

SWR has no fetchQuery. preload(key, fetcher) keeps the result in the global cache, where a useSWR call with the same key reads it.

10,000 / 10,000 rows loaded · fetching…each window cached globally by SWR
ID
Name
Email
Score
pnpm dlx shadcn@latest add @gridcn/data-grid-lazy-swr-demo

The key is a tuple of the spec key and the block, so each sort, filter, and block gets its own entry:

import { mutate, preload } from "swr";
import { serverSpecKey } from "@/components/data-grid/data-grid";
import {
  useDataGridServerRows,
} from "@/components/data-grid-server/data-grid-server";

type Person = { id: string; name: string };
type Block = { rows: Person[]; totalRowCount: number };

export function useSwrPeople() {
  return useDataGridServerRows<Person>({
    mode: "scroll",
    fetchRows: ({ spec, start, end }) => {
      const key = ["people", serverSpecKey(spec), start, end] as const;
      const fetcher = async (): Promise<Block> => {
        const body = JSON.stringify({ spec, start, end });
        const init = { method: "POST", body };
        const response = await fetch("/api/people", init);
        const answer = await response.json();
        return { rows: answer.rows, totalRowCount: answer.total };
      };
      return preload(key, fetcher).catch((error: unknown) => {
        void mutate(key);
        throw error;
      });
    },
  });
}

Do not pass the request signal to the fetcher. preload caches the promise, so an aborted block stays a rejection and fails again when the block scrolls back. The catch clears the entry of a failed block with mutate(key), so retry() fetches it again. See Fetch with a cache for the limits of each cache.

On this page