Component documentation

DataTable

  • Generic, fully typed, built from scratch — no table library.
  • Every example below is live; its code is read from the real source file at build time, so it cannot drift.
  • The timetable is the production usage. This page is the reference.

Getting started

One import, three folders

  • Vendored, not installed — it lives in the repo so it can be edited.
  • Split by kind, re-exported from one entry point. Nothing reaches past it.
  • lib/data-table is React-free: sorting, filtering and paging are plain functions over arrays.
folder layout
components/ui/data-table/   rendering
hooks/data-table/           state
lib/data-table/             pure logic, no React
anywhere.tsx
import {
  DataTable,        // the preset
  Parts,            // the same thing, taken apart
  useDataTable,     // all of the state
  defineColumns,
  createColumnHelper,
} from "@/components/ui/data-table";

The API

Columns drive everything

  • No row shape is hard-coded. A column says how to read a value, how to render it, and what the table may do with it.
  • accessor columns feed sorting, search and filtering. display columns (a row menu, a checkbox) opt out of all three.
  • The value type is closed over at construction, so columns of different types share one array with no any.
idstring
Stable key. Sort and filter state refer to it, never to an index.
accessor(row) => TValue
The sortable value. Sort the raw number or date; format in the cell.
cell(ctx) => ReactNode
Custom render. Gets value, row, rowIndex — not the table.
sortableboolean
Opt-in. Without it, not sortable from the header or from controlled state.
searchable / filterableboolean
Include in search; give the column its own facet button.
width / minWidthnumber
Fixed layout — widths never depend on content.
pinned"left"
Sticky on horizontal scroll. Offsets computed from the pinned columns before it.
hideable / defaultHiddenboolean
Whether the Columns menu may hide it; whether it starts hidden.
cardLabel / hideOnCardstring | boolean
Behaviour in the mobile card layout, which has no header row.
features/docs/examples/members.columns.tsx
import { Badge } from "@/components/ui/Badge";
import { createColumnHelper, defineColumns } from "@/components/ui/data-table";
import type { Member } from "./members.data";

const column = createColumnHelper<Member>();

export const memberColumns = defineColumns<Member>([
  column.accessor((row) => row.name, {
    id: "name",
    header: "Member",
    width: 220,
    pinned: "left",
    sortable: true,
    searchable: true,
    hideable: false,
    cell: ({ value, row }) => (
      <div className="min-w-0">
        <p className="truncate font-medium text-ink">{value}</p>
        <p className="truncate text-xs text-muted">{row.email}</p>
      </div>
    ),
  }),

  column.accessor((row) => row.tier, {
    id: "tier",
    header: "Tier",
    width: 150,
    sortable: true,
    filterable: true,
    cell: ({ value }) => (
      <Badge tone={value === "Annual" ? "success" : value === "Monthly" ? "accent" : "neutral"}>
        {value}
      </Badge>
    ),
  }),


  column.accessor((row) => row.visits, {
    id: "visits",
    header: "Visits",
    width: 130,
    align: "right",
    sortable: true,
    cell: ({ value }) => (
      <span className="tabular-nums">{value.toLocaleString("en-US")}</span>
    ),
  }),

  column.accessor((row) => row.bookings.length, {
    id: "bookings",
    header: "Bookings",
    width: 130,
    align: "right",
    sortable: true,
    defaultHidden: true,
  }),
]);

Variant

The preset

  • Two calls: useDataTable for state, DataTable for the default arrangement.
  • Sorting, search, facet filters, column visibility, pagination — all client-side, all on by default.
  • Try the Columns menu: Bookings starts hidden.

Members

Sorting, search, facet filters, column visibility and pagination — all client-side, all from the defaults.

  • Yuki Tanaka

    yuki@example.com

    Tier
    Annual
    Visits
    203
  • Amara Osei

    amara@example.com

    Tier
    Annual
    Visits
    148
  • Sofia Marchetti

    sofia@example.com

    Tier
    Annual
    Visits
    112
  • Priya Raman

    priya@example.com

    Tier
    Monthly
    Visits
    61
  • Kwame Boateng

    kwame@example.com

    Tier
    Monthly
    Visits
    55
features/docs/examples/BasicUsage.tsx
import { DataTable, useDataTable } from "@/components/ui/data-table";
import { MEMBERS } from "./members.data";
import type { Member } from "./members.data";
import { memberColumns } from "./members.columns";

export function BasicUsage() {
  const table = useDataTable<Member>({
    data: MEMBERS,
    columns: memberColumns,
    getRowId: (row) => row.id,
    defaultSort: { columnId: "visits", direction: "desc" },
    defaultPagination: { pageIndex: 0, pageSize: 5 },
  });

  return (
    <DataTable
      table={table}
      title="Members"
      description="Sorting, search, facet filters, column visibility and pagination — all client-side, all from the defaults."
      searchPlaceholder="Search members…"
      emptyMessage="No members match this view."
    />
  );
}

Variant

No header, no toolbar

  • hideToolbar drops search and filters. showHeader={false} drops the header row.
  • Two booleans, not a second component — the state and row rendering are identical.
  • For tables embedded in a card, a sidebar or a print view.
  • Amara Osei

    amara@example.com

    Tier
    Annual
    Visits
    148
  • Priya Raman

    priya@example.com

    Tier
    Monthly
    Visits
    61
  • Desmond Lee

    desmond@example.com

    Tier
    Drop-in
    Visits
    4
  • Yuki Tanaka

    yuki@example.com

    Tier
    Annual
    Visits
    203
features/docs/examples/HeaderlessUsage.tsx
import { DataTable, useDataTable } from "@/components/ui/data-table";
import { MEMBERS } from "./members.data";
import type { Member } from "./members.data";
import { memberColumns } from "./members.columns";

export function HeaderlessUsage() {
  const table = useDataTable<Member>({
    data: MEMBERS.slice(0, 4),
    columns: memberColumns,
    getRowId: (row) => row.id,
    defaultPagination: { pageIndex: 0, pageSize: 4 },
  });

  return <DataTable table={table} hideToolbar showHeader={false} />;
}

Variant

Composed from parts

  • Different order, different subset, app-specific actions — compose instead of growing DataTable's props.
  • Every part reads the instance from context. No prop drilling, no second source of truth.
  • DataTable is literally this composition in its default order.
Parts.Root
Provides the instance and the bordered surface.
Parts.Header
Title, description, actions slot.
Parts.Toolbar / Spacer
Control row; spacer pushes what follows to the end.
Parts.Search
Bound to search state. Debouncing is the caller's job in server mode.
Parts.Filter / Filters
One facet button by column id, or one per filterable column.
Parts.ClearFilters
Clears filters and search. Hidden when there is nothing to clear.
Parts.ColumnToggle
Visibility menu. Refuses to hide the last visible column.
Parts.Body
Table on desktop, cards on mobile, plus loading / empty / error.
Parts.Pagination
Page size, range, navigation. Hidden in the error state.

Members

Toolbar rebuilt: one named facet, a clear-all beside it, an app action on the right, and no column-visibility menu.

  • Amara Osei

    amara@example.com

    Tier
    Annual
    Visits
    148
  • Priya Raman

    priya@example.com

    Tier
    Monthly
    Visits
    61
  • Desmond Lee

    desmond@example.com

    Tier
    Drop-in
    Visits
    4
  • Yuki Tanaka

    yuki@example.com

    Tier
    Annual
    Visits
    203
  • Noor Haddad

    noor@example.com

    Tier
    Monthly
    Visits
    37
features/docs/examples/ComposedUsage.tsx
import { Parts, useDataTable } from "@/components/ui/data-table";
import { Button } from "@/components/ui/Button";
import { MEMBERS } from "./members.data";
import type { Member } from "./members.data";
import { memberColumns } from "./members.columns";

export function ComposedUsage() {
  const table = useDataTable<Member>({
    data: MEMBERS,
    columns: memberColumns,
    getRowId: (row) => row.id,
    defaultPagination: { pageIndex: 0, pageSize: 5 },
  });

  return (
    <Parts.Root table={table}>
      <Parts.Header
        title="Members"
        description="Toolbar rebuilt: one named facet, a clear-all beside it, an app action on the right, and no column-visibility menu."
        actions={<Button size="sm" variant="primary">Invite member</Button>}
      />
      <Parts.Toolbar>
        <Parts.Search placeholder="Search members…" />
        <Parts.Filter columnId="tier" />
        <Parts.ClearFilters />
      </Parts.Toolbar>
      <Parts.Body emptyMessage="No members match this view." />
      <Parts.Pagination />
    </Parts.Root>
  );
}

Expandable rows — mode (a)

Children that arrive with the parent

  • getChildren reads rows already in memory.
  • getCanExpand decides which rows get a chevron at all.
  • The transition animates grid-template-rows, not height — no measurement, no JS per frame.
  • Amara Osei

    amara@example.com

    Tier
    Annual
    Visits
    148
  • Priya Raman

    priya@example.com

    Tier
    Monthly
    Visits
    61
  • Desmond Lee

    desmond@example.com

    Tier
    Drop-in
    Visits
    4
  • Yuki Tanaka

    yuki@example.com

    Tier
    Annual
    Visits
    203
  • Noor Haddad

    noor@example.com

    Tier
    Monthly
    Visits
    37
features/docs/examples/ExpansionUsage.tsx
import { useMemo } from "react";
import { DataTable, useDataTable } from "@/components/ui/data-table";
import type { ExpansionConfig } from "@/components/ui/data-table";
import { Badge } from "@/components/ui/Badge";
import { MEMBERS } from "./members.data";
import { memberColumns } from "./members.columns";
import type { Booking, Member } from "./members.data";

export function ExpansionUsage() {
  const expansion = useMemo<ExpansionConfig<Member, Booking>>(
    () => ({
      getCanExpand: (row) => row.tier !== "Drop-in",
      getChildren: (row) => row.bookings,
      emptyMessage: "No bookings on record for this member.",
      renderChildren: (bookings) => (
        <ul className="space-y-2">
          {bookings.map((booking) => (
            <li key={booking.id} className="flex items-center gap-3 text-sm">
              <span className="w-40 shrink-0 truncate text-ink">{booking.title}</span>
              <span className="w-28 shrink-0 tabular-nums text-muted">{booking.date}</span>
              <Badge tone={booking.status === "Attended" ? "success" : "danger"}>
                {booking.status}
              </Badge>
            </li>
          ))}
        </ul>
      ),
    }),
    [],
  );

  const table = useDataTable<Member, Booking>({
    data: MEMBERS,
    columns: memberColumns,
    getRowId: (row) => row.id,
    defaultPagination: { pageIndex: 0, pageSize: 5 },
    expansion,
  });

  return <DataTable table={table} hideToolbar />;
}

Expandable rows — mode (b)

Children fetched on expand

  • Swap getChildren for loadChildren and the table owns the async lifecycle: skeleton, empty, retryable error.
  • Responses are cached per row and guarded by a request token — a slow reply cannot overwrite a newer one.
  • Flip “Fail child fetch” above to see the failure path.

Class timetable — on-demand children

Parent rows arrive without attendees. Children are fetched on first expand, then cached.

features/timetable/TimetableView.tsx
import { useCallback, useMemo } from "react";
import { DataTable, useDataTable } from "@/components/ui/data-table";
import type { ExpansionConfig } from "@/components/ui/data-table";
import type { Attendee, ClassRow } from "@/lib/data";
import { fetchAttendees, fetchClasses, fetchClassesWithoutAttendees } from "@/lib/api/client";
import { useQuery } from "@/hooks/useQuery";
import { useFaults } from "@/lib/dev/faults";
import { AttendeeTable } from "./AttendeeTable";
import { timetableColumns } from "./columns";

export type ChildMode = "inline" | "on-demand";

export function TimetableView({
  mode = "inline",
  title,
  description,
}: {
  mode?: ChildMode;
  title?: string;
  description?: string;
}) {
  const faults = useFaults();

  const key = `classes:${mode}:${faults.latencyMs}:${faults.failInitialFetch}:${faults.emptyDataset}`;

  const fetcher = useCallback(
    (signal: AbortSignal) =>
      mode === "inline"
        ? fetchClasses(signal)
        : fetchClassesWithoutAttendees(signal),
    [mode],
  );

  const { data, status, error, refetch } = useQuery<ClassRow[]>(key, fetcher);

  const rows = useMemo(() => data ?? [], [data]);
  const getRowId = useCallback((row: ClassRow) => row.id, []);

  const expansion = useMemo<ExpansionConfig<ClassRow, Attendee>>(
    () => ({
      getCanExpand: (row) => row.status !== "Cancelled",
      getChildren:
        mode === "inline" ? (row) => row.attendees : () => undefined,
      loadChildren:
        mode === "on-demand"
          ? (row) => fetchAttendees(row.id)
          : undefined,
      renderChildren: (attendees) => <AttendeeTable attendees={attendees} />,
      emptyMessage: "Nobody has booked this class yet.",
    }),
    [mode],
  );

  const table = useDataTable<ClassRow, Attendee>({
    data: rows,
    columns: timetableColumns,
    getRowId,
    status,
    error,
    onRetry: refetch,
    defaultSort: { columnId: "time", direction: "asc" },
    defaultPagination: { pageIndex: 0, pageSize: 10 },
    expansion,
  });

  return (
    <DataTable
      table={table}
      title={title ?? "Class timetable"}
      description={
        description ??
        "Today's schedule. Expand a class to see who is booked in."
      }
      searchPlaceholder="Search classes or instructors…"
      emptyMessage="No classes are scheduled for this day."
      maxHeight={620}
    />
  );
}

Second dataset · server-driven

Controlled sort, filters and pagination

  • Different row type, different column types, 2,000 rows, same component.
  • manual tells the table which work the owner took over; it then emits changes instead of applying them.
  • Under manual.pagination the types require serverTotal — a table holding one page cannot count the rest.
  • facets are supplied for the same reason: options derived from the visible page would shrink as you page.
  • This shell is composed from the parts, not the preset.

Invoices

2,000 rows served one page at a time. Sort, search, filters and paging all round-trip to the mock API; the facet lists come from the full dataset, not the page on screen.

features/invoices/InvoicesView.tsx
import { useCallback, useEffect, useMemo, useState } from "react";
import { Parts, useDataTable } from "@/components/ui/data-table";
import type { FilterState, PaginationState, SortState } from "@/components/ui/data-table";
import type { InvoiceRow } from "@/lib/data";
import { fetchInvoices } from "@/lib/api/client";
import { useQuery } from "@/hooks/useQuery";
import { useFaults } from "@/lib/dev/faults";
import { invoiceColumns } from "./columns";

const MANUAL = {
  sort: true,
  pagination: true,
  search: true,
  filter: true,
} as const;
const PAGE_SIZES = [10, 25, 50];


export function InvoicesView() {
  const faults = useFaults();

  const [sort, setSort] = useState<SortState | null>({
    columnId: "issuedAt",
    direction: "desc",
  });
  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 25,
  });
  const [search, setSearch] = useState("");
  const [debouncedSearch, setDebouncedSearch] = useState("");
  const [filters, setFilters] = useState<FilterState>({});

  useEffect(() => {
    const timer = setTimeout(() => setDebouncedSearch(search), 300);
    return () => clearTimeout(timer);
  }, [search]);

  const request = useMemo(
    () => ({
      pageIndex: pagination.pageIndex,
      pageSize: pagination.pageSize,
      sort,
      search: debouncedSearch,
      filters,
    }),
    [pagination.pageIndex, pagination.pageSize, sort, debouncedSearch, filters],
  );

  const key = `invoices:${JSON.stringify(request)}:${faults.latencyMs}:${faults.failInitialFetch}:${faults.emptyDataset}`;

  const fetcher = useCallback(
    (signal: AbortSignal) => fetchInvoices(request, signal),
    [request],
  );

  const { data, status, error, refetch } = useQuery(key, fetcher, {
    keepPreviousData: true,
  });

  const rows = useMemo(() => data?.rows ?? [], [data]);
  const getRowId = useCallback((row: InvoiceRow) => row.id, []);

  const handleSearchChange = useCallback((value: string) => {
    setSearch(value);
    setPagination((previous) =>
      previous.pageIndex === 0 ? previous : { ...previous, pageIndex: 0 },
    );
  }, []);

  const table = useDataTable<InvoiceRow>({
    data: rows,
    columns: invoiceColumns,
    getRowId,
    manual: MANUAL,
    serverTotal: data?.total ?? 0,
    status,
    error,
    onRetry: refetch,
    sort,
    onSortChange: setSort,
    pagination,
    onPaginationChange: setPagination,
    search,
    onSearchChange: handleSearchChange,
    filters,
    onFiltersChange: setFilters,
    facets: data?.facets,
    pageSizeOptions: PAGE_SIZES,
  });

  return (
    <Parts.Root table={table}>
      <Parts.Header
        title="Invoices"
        description="2,000 rows served one page at a time. Sort, search, filters and paging all round-trip to the mock API; the facet lists come from the full dataset, not the page on screen."
      />
      <Parts.Toolbar>
        <Parts.Search placeholder="Search invoice number or customer…" />
        <Parts.Filter columnId="status" />
        <Parts.Filter columnId="plan" />
        <Parts.Filter columnId="method" />
        <Parts.ClearFilters />
        <Parts.Spacer />
        <Parts.ColumnToggle />
      </Parts.Toolbar>
      <Parts.Body maxHeight={620} emptyMessage="No invoices match this view." />
      <Parts.Pagination />
    </Parts.Root>
  );
}

Edge cases

Loading, empty and error

  • Skeleton rows match the real column layout — same widths, same pinned column — so nothing shifts when data lands.
  • The empty state knows whether it is empty or filtered, and offers to clear in the second case.
  • Errors replace the body, keep the toolbar, and retry through the caller's refetch.
  • The fault injector at the top forces latency, a failed parent fetch, a failed child fetch, or an empty dataset.