# Data Table Pattern

import { Callout } from "fumadocs-ui/components/callout";
import { Accordion, Accordions } from "fumadocs-ui/components/accordion";
import { Step, Steps } from "fumadocs-ui/components/steps";
import { Tabs, Tab } from "fumadocs-ui/components/tabs";
import {
  Badge,
  Card,
  CardContent,
  CardHeader,
  CardTitle,
} from "@pycolors/ui";
import {
  AlertCircle,
  ArrowRight,
  CheckCircle,
  Filter,
  LoaderCircle,
  PanelsTopLeft,
  ShieldCheck,
  Table2,
  Workflow,
  XCircle,
} from "lucide-react";
import { PreferAvoid } from '@/components/docs/prefer-avoid';
import { DocsLinks } from "@/components/docs/docs-links";
import { DocsFeatureGrid } from "@/components/docs/docs-feature-grid";
import { DocsConceptTabs } from "@/components/docs/docs-concept-tabs";

import {
  DataTableLoading,
  DataTableEmpty,
  DataTableError,
  DataTableWithFiltersSheet,
  DataTableRowActionsMenu,
} from "../previews/data-table";

<div className="flex flex-wrap items-center gap-2">
  <Badge variant="outline">
    Patterns
  </Badge>

  <Badge>
    Data table
  </Badge>
</div>

## Overview

Data tables are a core SaaS dashboard pattern.

They power admin views, billing screens, customer lists, logs, subscriptions, projects, invoices, and operational workflows. A production-ready table is not only rows and columns. It is a complete interface for understanding, filtering, acting on, and navigating structured data.

Use this pattern when users need to:

* scan repeatable records
* compare structured values
* filter or search a dataset
* act on individual rows
* move through paginated results
* recover from loading, empty, and error states

<Callout title="Why this matters">
  Tables are where product complexity becomes visible. If loading, filters, row actions, and pagination feel inconsistent, the entire dashboard feels less reliable.
</Callout>

## What you’ll build

<DocsFeatureGrid
  columns={3}
  tone="platform"
  items={[
  {
    title: 'Table anatomy',
    description:
      'Structure the surface into header, toolbar, table, row actions, footer, and async states.',
    icon: Table2,
  },
  {
    title: 'Controls',
    description:
      'Add search, filters, bulk actions, and responsive row controls without crowding the UI.',
    icon: Filter,
  },
  {
    title: 'Production states',
    description:
      'Handle loading, empty, error, pagination, mutation, and recovery states clearly.',
    icon: ShieldCheck,
  },
]}
/>

## Mental model

> The table renders structure.
> The data layer owns truth.
> The toolbar controls intent.
> The footer handles navigation.

| Area        | Responsibility                                           |
| ----------- | -------------------------------------------------------- |
| Header      | Page context and primary actions                         |
| Toolbar     | Search, filters, bulk actions, and view controls         |
| Table       | Rows, columns, selection, and row rendering              |
| Row actions | Contextual actions for one record                        |
| Footer      | Pagination, counts, and selection summary                |
| Data layer  | Fetching, sorting, filtering, permissions, and mutations |

<Callout type="info" title="System rule">
  A table should not own the data source. Keep fetching, filtering, sorting, permissions, and mutations in the feature layer.
</Callout>

## Steps

<Steps>
  <Step>
    ### Define the anatomy

    A production table is composed from distinct areas. Each area should evolve independently.

    ```tsx title="components/projects-table.tsx"
    export function ProjectsTable() {
      return (
        <section className="space-y-4">
          <ProjectsTableHeader />
          <ProjectsTableToolbar />
          <ProjectsTableContent />
          <ProjectsTableFooter />
        </section>
      );
    }
    ```

    This keeps the table flexible when product requirements grow.
  </Step>

  <Step>
    ### Keep data outside the table

    The table should receive data, status, and callbacks. It should not own fetching, permission checks, or mutation rules.

    ```tsx title="features/projects/projects-table-container.tsx"
    export function ProjectsTableContainer() {
      const projects = useProjects();
      const filters = useProjectFilters();

      return (
        <ProjectsTable
          data={projects.data}
          status={projects.status}
          filters={filters.value}
          onFiltersChange={filters.setValue}
          onRetry={projects.refetch}
        />
      );
    }
    ```

    The feature layer owns truth. The table renders the current state.
  </Step>

  <Step>
    ### Design states before rows

    Every table needs explicit loading, empty, and error states.

    <Tabs items={["Loading", "Empty", "Error"]}>
      <Tab value="Loading">
        <DataTableLoading />
      </Tab>

      <Tab value="Empty">
        <DataTableEmpty />
      </Tab>

      <Tab value="Error">
        <DataTableError />
      </Tab>
    </Tabs>

    Do not add these states at the end. They define the production feel of the table.
  </Step>

  <Step>
    ### Add controls deliberately

    Filters and row actions should support the task without making the table feel crowded.

    Use progressive disclosure:

    * inline controls for frequent filters
    * `Sheet` for advanced filters
    * `DropdownMenu` for secondary row actions
    * confirmation or recovery for destructive actions

    <Tabs items={["Filters", "Row actions"]}>
      <Tab value="Filters">
        <DataTableWithFiltersSheet />
      </Tab>

      <Tab value="Row actions">
        <DataTableRowActionsMenu />
      </Tab>
    </Tabs>
  </Step>
</Steps>

## Anatomy

A scalable table has clear regions.

| Region  | What belongs there                     | What to avoid                   |
| ------- | -------------------------------------- | ------------------------------- |
| Header  | title, description, primary action     | data fetching logic             |
| Toolbar | search, filters, bulk actions          | every possible control at once  |
| Table   | rows, columns, selection, row actions  | business rules and server logic |
| Footer  | pagination, item count, selected count | hidden navigation state         |

<Callout title="Why this matters">
  When responsibilities are separated, the table can grow without becoming a single fragile component.
</Callout>

## States

A production table handles more than loading and success.

| State      | Component             | Goal                                  |
| ---------- | --------------------- | ------------------------------------- |
| Loading    | `Skeleton`            | Preserve shape while data is expected |
| Empty      | `EmptyState`          | Explain valid empty results           |
| Error      | `Alert`               | Explain failure and recovery          |
| Filtering  | Toolbar state         | Show active constraints clearly       |
| Mutating   | Inline state or toast | Confirm action progress and recovery  |
| Paginating | Footer state          | Keep navigation predictable           |

Never use the same feedback pattern for every state. Loading data, deleting a row, saving filters, and changing pages are different user experiences.

## Variations

<DocsConceptTabs
  items={[
  {
    value: 'Simple',
    title: 'Simple table',
    icon: Table2,
    description: (
      <>
        <p>
          Use when the dataset is small and users mainly need to scan records.
        </p>

        <div className="mt-4 flex flex-wrap gap-2">
          <Badge variant="outline">Minimal row actions</Badge>
          <Badge variant="outline">Simple pagination</Badge>
          <Badge variant="outline">Clear empty state</Badge>
          <Badge variant="outline">No advanced filters</Badge>
        </div>
      </>
    ),
  },
  {
    value: 'Filtered',
    title: 'Filtered table',
    icon: Filter,
    description: (
      <>
        <p>
          Use when users need to narrow results across multiple dimensions.
        </p>

        <div className="mt-4 flex flex-wrap gap-2">
          <Badge variant="outline">Search input</Badge>
          <Badge variant="outline">Filter sheet</Badge>
          <Badge variant="outline">Active filter summary</Badge>
          <Badge variant="outline">Reset filters action</Badge>
        </div>
      </>
    ),
  },
  {
    value: 'Operational',
    title: 'Operational table',
    icon: Workflow,
    description: (
      <>
        <p>
          Use when users frequently perform actions directly on records.
        </p>

        <div className="mt-4 flex flex-wrap gap-2">
          <Badge variant="outline">Row actions</Badge>
          <Badge variant="outline">Bulk actions</Badge>
          <Badge variant="outline">Confirmation dialogs</Badge>
          <Badge variant="outline">Retry and undo flows</Badge>
        </div>
      </>
    ),
  },
]}
/>

## Decision guide

Use this pattern if:

* the page displays structured repeatable data
* users need to scan, filter, compare, or act on rows
* the table appears in a dashboard or admin surface
* loading, empty, and error states matter
* pagination, row actions, or bulk actions are required

Avoid this pattern if:

* content is editorial or marketing-focused
* data is better represented as cards, a timeline, or a feed
* the user only needs a single summary value
* mobile-first scanning is more important than tabular comparison
* the table would hide the primary product action

<PreferAvoid
  prefer={[
  'explicit loading, empty, and error states',
  'controlled pagination and filtering',
  'row actions in contextual menus',
  'progressive filters for complex datasets',
  'clear ownership between data layer and UI',
]}
  avoid={[
  'fetching data inside a visual table primitive',
  'using a table for non-tabular content',
  'hiding blocking failures behind only a toast',
  'crowding the toolbar with every possible filter',
  'destructive row actions without confirmation or recovery',
]}
/>

## Production checklist

Before shipping a data table, confirm that:

* loading preserves the expected layout
* empty state explains the result and next action
* error state includes recovery or retry
* pagination is controlled and predictable
* filters can be cleared
* active filters are visible
* row actions are keyboard accessible
* destructive actions require confirmation or recovery
* selection state is clear when bulk actions exist
* mobile behavior is defined

<Callout title="Ready to turn this pattern into a real SaaS surface?">
  Starter Pro gives you a stronger foundation for production dashboards, protected routes, auth, billing, and backend-backed product flows. → `/docs/starter-pro`
</Callout>

## Common questions

<Accordions type="single">
  <Accordion title="Should the table fetch its own data?">
    Prefer keeping data fetching outside the table. The table should render data and expose callbacks. The feature layer should own fetching, permissions, filtering, and mutations.
  </Accordion>

  <Accordion title="When should filters move into a Sheet?">
    Move filters into a Sheet when the toolbar becomes crowded, filters are secondary, or the mobile experience needs a cleaner interaction model.
  </Accordion>

  <Accordion title="Should row actions always be in a dropdown?">
    Use a dropdown for secondary or contextual actions. Keep the primary row action visible only when it is the main reason users visit the table.
  </Accordion>
</Accordions>

## Next steps

<DocsLinks
  variant="grid"
  tone="platform"
  items={[
  {
    title: 'Async actions',
    href: '/docs/patterns/async-actions',
    description:
      'Design save, delete, retry, undo, and optimistic mutation flows.',
    icon: LoaderCircle,
  },
  {
    title: 'Empty, loading, and error states',
    href: '/docs/guides/empty-loading-error',
    description:
      'Learn how to communicate async states consistently across product surfaces.',
    icon: AlertCircle,
  },
  {
    title: 'Table',
    href: '/docs/ui/table',
    description:
      'Review the primitive used to render structured tabular content.',
    icon: Table2,
  },
  {
    title: 'Building a SaaS layout',
    href: '/docs/guides/building-a-saas-layout',
    description:
      'Place tables inside scalable dashboard layouts with navigation and content structure.',
    icon: PanelsTopLeft,
  },
]}
/>