Next.js course Β· Module 9: Integrations and Advanced Features

Next.js with TanStack Table - Advanced data tables

22 min read Β·
In this lesson11

The guardians' panel of Metropolis Quantum shows thousands of records: users, roles, statuses. A plain table element with a map loop is enough for a week, and then someone asks for sorting, a search box, pagination and selecting many rows at once. Writing all of that by hand means hundreds of lines of fragile logic. Matrix, the data architect of the Metropolis, solves it with TanStack Table - a library that computes the table logic and leaves the look to you.

What is TanStack Table?

TanStack Table (formerly React Table) is a headless library for building tables that offers:

  • Headless UI - full control over the look
  • TypeScript-first - full typing support
  • Framework agnostic - works with React, Vue, Svelte
  • Feature-rich - sorting, filtering, pagination, grouping
  • Performance - optimizations for large datasets
  • Extensible - a rich plugin system

"Headless" means the library renders no HTML at all. You get an API with state and methods, and you write the markup and styles yourself.

Advantages of TanStack Table

  • No UI dependencies - no ready-made components or styles
  • Tree-shakable - only the features you need in the bundle
  • Server-side support - ideal for SSR/SSG
  • Accessibility - accessibility depends on your HTML, because you write it
  • Mobile-friendly - responsive tables

What TanStack Table does NOT do: it does not fetch data and has no built-in virtualization. You supply the data yourself (for example with TanStack Query), and virtualization of long lists comes from the separate TanStack Virtual library.

Installation and basic setup

Installation

In a React project you install the @tanstack/react-table adapter, which already contains the library core:

# Install TanStack Table
npm install @tanstack/react-table

# Framework-agnostic core (react-table installs it automatically)
npm install @tanstack/table-core

The @tanstack/table-core package is the framework-agnostic core. The React adapter installs it automatically, so a separate installation is optional.

Basic table

Every table starts with a data type. The User interface describes one row, and literal unions, such as 'admin' | 'user' | 'moderator', limit the allowed values:

// types/User.ts
export interface User {
  id: string;
  name: string;
  email: string;
  role: 'admin' | 'user' | 'moderator';
  status: 'active' | 'inactive' | 'pending';
  createdAt: string;
  lastLogin?: string;
}

Based on this, TypeScript will suggest column names and catch typos in keys.

Now we define the columns. The createColumnHelper<User>() function creates a helper whose accessor method points to an object field, while cell decides how to render the value:

// components/UsersTable.tsx
'use client';

import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  useReactTable,
} from '@tanstack/react-table';
import { User } from '@/types/User';

const columnHelper = createColumnHelper<User>();

const columns = [
  columnHelper.accessor('name', {
    header: 'Username',
    cell: (info) => info.getValue(),
  }),
  columnHelper.accessor('email', {
    header: 'Email',
    cell: (info) => (
      <a href={`mailto:${info.getValue()}`} className="text-blue-600 hover:underline">
        {info.getValue()}
      </a>
    ),
  }),
  columnHelper.accessor('role', {
    header: 'Role',
    cell: (info) => {
      const role = info.getValue();
      const roleColors = {
        admin: 'bg-red-100 text-red-800',
        moderator: 'bg-yellow-100 text-yellow-800',
        user: 'bg-green-100 text-green-800',
      };

      return (
        <span className={`px-2 py-1 rounded-full text-xs font-medium ${roleColors[role]}`}>
          {role}
        </span>
      );
    },
  }),
  columnHelper.accessor('status', {
    header: 'Status',
    cell: (info) => {
      const status = info.getValue();
      const statusColors = {
        active: 'bg-green-100 text-green-800',
        inactive: 'bg-gray-100 text-gray-800',
        pending: 'bg-yellow-100 text-yellow-800',
      };

      return (
        <span className={`px-2 py-1 rounded-full text-xs font-medium ${statusColors[status]}`}>
          {status}
        </span>
      );
    },
  }),
  columnHelper.accessor('createdAt', {
    header: 'Created at',
    cell: (info) => new Date(info.getValue()).toLocaleDateString('en-US'),
  }),
];

The columns are just an array of configuration, with no table yet. Role and status get colored badges, and the date is formatted for the US English locale.

The component connects data and columns with the useReactTable hook. The minimal configuration is data, columns and getCoreRowModel, the basic row model:

interface UsersTableProps {
  data: User[];
}

export default function UsersTable({ data }: UsersTableProps) {
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
  });

  return (
    <div className="overflow-x-auto">
      <table className="min-w-full bg-white border border-gray-200">
        <thead className="bg-gray-50">
          {table.getHeaderGroups().map((headerGroup) => (
            <tr key={headerGroup.id}>
              {headerGroup.headers.map((header) => (
                <th
                  key={header.id}
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                >
                  {header.isPlaceholder
                    ? null
                    : flexRender(header.column.columnDef.header, header.getContext())}
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody className="bg-white divide-y divide-gray-200">
          {table.getRowModel().rows.map((row) => (
            <tr key={row.id} className="hover:bg-gray-50">
              {row.getVisibleCells().map((cell) => (
                <td key={cell.id} className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

flexRender renders a header or a cell regardless of whether the definition holds text or a function. All the HTML and Tailwind classes are ours: the library only provided header groups and rows.

Sorting and filtering

Sorting

Every table feature follows the same scheme: state in useState, wiring it through state and on...Change, and adding the matching row model. For sorting that means SortingState and getSortedRowModel:

// components/SortableUsersTable.tsx
'use client';

import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  getSortedRowModel,
  SortingState,
  useReactTable,
} from '@tanstack/react-table';
import { useState } from 'react';
import { ChevronUpIcon, ChevronDownIcon } from '@heroicons/react/24/outline';
import { User } from '@/types/User';

const columnHelper = createColumnHelper<User>();

const columns = [
  columnHelper.accessor('name', {
    header: 'Username',
    enableSorting: true,
  }),
  columnHelper.accessor('email', {
    header: 'Email',
    enableSorting: true,
  }),
  columnHelper.accessor('role', {
    header: 'Role',
    enableSorting: true,
  }),
  columnHelper.accessor('status', {
    header: 'Status',
    enableSorting: true,
  }),
  columnHelper.accessor('createdAt', {
    header: 'Created at',
    enableSorting: true,
    sortingFn: 'datetime',
    cell: (info) => new Date(info.getValue()).toLocaleDateString('en-US'),
  }),
];

interface SortableUsersTableProps {
  data: User[];
}

export default function SortableUsersTable({ data }: SortableUsersTableProps) {
  const [sorting, setSorting] = useState<SortingState>([]);

  const table = useReactTable({
    data,
    columns,
    state: {
      sorting,
    },
    onSortingChange: setSorting,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
  });

  return (
    <div className="overflow-x-auto">
      <table className="min-w-full bg-white border border-gray-200">
        <thead className="bg-gray-50">
          {table.getHeaderGroups().map((headerGroup) => (
            <tr key={headerGroup.id}>
              {headerGroup.headers.map((header) => (
                <th
                  key={header.id}
                  className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                >
                  <div
                    className={
                      header.column.getCanSort()
                        ? 'flex items-center cursor-pointer select-none hover:text-gray-700'
                        : ''
                    }
                    onClick={header.column.getToggleSortingHandler()}
                  >
                    {flexRender(header.column.columnDef.header, header.getContext())}
                    {header.column.getCanSort() && (
                      <span className="ml-1">
                        {header.column.getIsSorted() === 'asc' ? (
                          <ChevronUpIcon className="w-4 h-4" />
                        ) : header.column.getIsSorted() === 'desc' ? (
                          <ChevronDownIcon className="w-4 h-4" />
                        ) : (
                          <div className="w-4 h-4" />
                        )}
                      </span>
                    )}
                  </div>
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody className="bg-white divide-y divide-gray-200">
          {table.getRowModel().rows.map((row) => (
            <tr key={row.id} className="hover:bg-gray-50">
              {row.getVisibleCells().map((cell) => (
                <td key={cell.id} className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

Clicking a header calls getToggleSortingHandler(), which cycles the order: ascending, descending, unsorted. sortingFn: 'datetime' sorts dates chronologically rather than alphabetically.

Filtering

Filtering adds two kinds of state: column filters (ColumnFiltersState) and one global filter for the search box. First the configuration with a custom globalFilterFn function:

// components/FilterableUsersTable.tsx
'use client';

import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  getFilteredRowModel,
  getSortedRowModel,
  SortingState,
  ColumnFiltersState,
  useReactTable,
  GlobalFilterTableState,
} from '@tanstack/react-table';
import { useState } from 'react';
import { MagnifyingGlassIcon } from '@heroicons/react/24/outline';
import { User } from '@/types/User';

// Global filter function
function globalFilterFn(row: any, columnId: string, value: string) {
  const search = value.toLowerCase();
  return (
    row.getValue('name')?.toLowerCase().includes(search) ||
    row.getValue('email')?.toLowerCase().includes(search) ||
    row.getValue('role')?.toLowerCase().includes(search)
  );
}

const columnHelper = createColumnHelper<User>();

const columns = [
  columnHelper.accessor('name', {
    header: 'Username',
    enableColumnFilter: true,
    filterFn: 'includesString',
  }),
  columnHelper.accessor('email', {
    header: 'Email',
    enableColumnFilter: true,
  }),
  columnHelper.accessor('role', {
    header: 'Role',
    enableColumnFilter: true,
    filterFn: 'equals',
  }),
  columnHelper.accessor('status', {
    header: 'Status',
    enableColumnFilter: true,
    filterFn: 'equals',
  }),
  columnHelper.accessor('createdAt', {
    header: 'Created at',
    enableColumnFilter: false,
    cell: (info) => new Date(info.getValue()).toLocaleDateString('en-US'),
  }),
];

interface FilterableUsersTableProps {
  data: User[];
}

export default function FilterableUsersTable({ data }: FilterableUsersTableProps) {
  const [sorting, setSorting] = useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
  const [globalFilter, setGlobalFilter] = useState('');

  const table = useReactTable({
    data,
    columns,
    state: {
      sorting,
      columnFilters,
      globalFilter,
    },
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    globalFilterFn,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
  });

You pick built-in filter functions, such as includesString or equals, by name. The getFilteredRowModel model drops rows that do not match the filters, and sorting keeps working on what is left.

The filter UI is made of ordinary form fields that set values through the table API:

  return (
    <div className="space-y-4">
      {/* Global Search */}
      <div className="flex items-center space-x-4">
        <div className="relative flex-1 max-w-sm">
          <MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
          <input
            value={globalFilter ?? ''}
            onChange={(e) => setGlobalFilter(e.target.value)}
            className="pl-10 pr-4 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500 w-full"
          />
        </div>

        {/* Roles Filter */}
        <select
          value={(table.getColumn('role')?.getFilterValue() as string) ?? ''}
          onChange={(e) =>
            table.getColumn('role')?.setFilterValue(e.target.value || undefined)
          }
          className="px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
        >
          <option value="">All roles</option>
          <option value="admin">Admin</option>
          <option value="moderator">Moderator</option>
          <option value="user">User</option>
        </select>

        {/* Status Filter */}
        <select
          value={(table.getColumn('status')?.getFilterValue() as string) ?? ''}
          onChange={(e) =>
            table.getColumn('status')?.setFilterValue(e.target.value || undefined)
          }
          className="px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500"
        >
          <option value="">All statuses</option>
          <option value="active">Active</option>
          <option value="inactive">Inactive</option>
          <option value="pending">Pending</option>
        </select>
      </div>

      {/* Results Info */}
      <div className="text-sm text-gray-600">
        Showing {table.getFilteredRowModel().rows.length} of {data.length} users
      </div>

      {/* Table */}
      <div className="overflow-x-auto">
        <table className="min-w-full bg-white border border-gray-200">
          <thead className="bg-gray-50">
            {table.getHeaderGroups().map((headerGroup) => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <th
                    key={header.id}
                    className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    <div
                      className={
                        header.column.getCanSort()
                          ? 'flex items-center cursor-pointer select-none hover:text-gray-700'
                          : ''
                      }
                      onClick={header.column.getToggleSortingHandler()}
                    >
                      {flexRender(header.column.columnDef.header, header.getContext())}
                    </div>
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {table.getRowModel().rows.map((row) => (
              <tr key={row.id} className="hover:bg-gray-50">
                {row.getVisibleCells().map((cell) => (
                  <td key={cell.id} className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

In tbody we use getRowModel(), because it returns the final result after filtering and sorting. getFilteredRowModel() would skip sorting, so here it only feeds the result counter.

Pagination

Pagination keeps the page number (pageIndex, counted from zero) and the page size (pageSize) in state. The getPaginationRowModel model slices the rows into pages:

// components/PaginatedUsersTable.tsx
'use client';

import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  getFilteredRowModel,
  PaginationState,
  useReactTable,
} from '@tanstack/react-table';
import { useState } from 'react';
import {
  ChevronLeftIcon,
  ChevronRightIcon,
  ChevronDoubleLeftIcon,
  ChevronDoubleRightIcon
} from '@heroicons/react/24/outline';
import { User } from '@/types/User';

const columnHelper = createColumnHelper<User>();

const columns = [
  columnHelper.accessor('name', {
    header: 'Username',
  }),
  columnHelper.accessor('email', {
    header: 'Email',
  }),
  columnHelper.accessor('role', {
    header: 'Role',
    cell: (info) => {
      const role = info.getValue();
      return (
        <span className="px-2 py-1 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
          {role}
        </span>
      );
    },
  }),
  columnHelper.accessor('status', {
    header: 'Status',
    cell: (info) => {
      const status = info.getValue();
      const colors = {
        active: 'bg-green-100 text-green-800',
        inactive: 'bg-gray-100 text-gray-800',
        pending: 'bg-yellow-100 text-yellow-800',
      };

      return (
        <span className={`px-2 py-1 rounded-full text-xs font-medium ${colors[status]}`}>
          {status}
        </span>
      );
    },
  }),
  columnHelper.accessor('createdAt', {
    header: 'Created at',
    cell: (info) => new Date(info.getValue()).toLocaleDateString('en-US'),
  }),
];

interface PaginatedUsersTableProps {
  data: User[];
}

export default function PaginatedUsersTable({ data }: PaginatedUsersTableProps) {
  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  });

  const table = useReactTable({
    data,
    columns,
    state: {
      pagination,
    },
    onPaginationChange: setPagination,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
  });

The table computes the number of pages from the number of rows and pageSize on its own. You do not need to keep a slice of the data in a separate variable.

The navigation controls use ready-made methods such as previousPage(), nextPage() and setPageIndex():

  return (
    <div className="space-y-4">
      {/* Table */}
      <div className="overflow-x-auto">
        <table className="min-w-full bg-white border border-gray-200">
          <thead className="bg-gray-50">
            {table.getHeaderGroups().map((headerGroup) => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <th
                    key={header.id}
                    className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    {flexRender(header.column.columnDef.header, header.getContext())}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {table.getRowModel().rows.map((row) => (
              <tr key={row.id} className="hover:bg-gray-50">
                {row.getVisibleCells().map((cell) => (
                  <td key={cell.id} className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between">
        <div className="flex items-center space-x-2">
          <span className="text-sm text-gray-700">
            Showing{' '}
            <span className="font-medium">
              {table.getState().pagination.pageIndex * table.getState().pagination.pageSize + 1}
            </span>{' '}
            -{' '}
            <span className="font-medium">
              {Math.min(
                (table.getState().pagination.pageIndex + 1) * table.getState().pagination.pageSize,
                table.getFilteredRowModel().rows.length
              )}
            </span>{' '}
            of{' '}
            <span className="font-medium">{table.getFilteredRowModel().rows.length}</span> results
          </span>

          <select
            value={table.getState().pagination.pageSize}
            onChange={(e) => {
              table.setPageSize(Number(e.target.value));
            }}
            className="px-3 py-1 border border-gray-300 rounded text-sm"
          >
            {[10, 20, 30, 40, 50].map((pageSize) => (
              <option key={pageSize} value={pageSize}>
                {pageSize} per page
              </option>
            ))}
          </select>
        </div>

        <div className="flex items-center space-x-2">
          <button
            onClick={() => table.setPageIndex(0)}
            disabled={!table.getCanPreviousPage()}
            className="p-2 border border-gray-300 rounded disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
          >
            <ChevronDoubleLeftIcon className="w-4 h-4" />
          </button>

          <button
            onClick={() => table.previousPage()}
            disabled={!table.getCanPreviousPage()}
            className="p-2 border border-gray-300 rounded disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
          >
            <ChevronLeftIcon className="w-4 h-4" />
          </button>

          <div className="flex items-center space-x-1">
            <span className="text-sm text-gray-700">Page</span>
            <input
              type="number"
              value={table.getState().pagination.pageIndex + 1}
              onChange={(e) => {
                const page = e.target.value ? Number(e.target.value) - 1 : 0;
                table.setPageIndex(page);
              }}
              className="w-16 px-2 py-1 border border-gray-300 rounded text-sm text-center"
              min={1}
              max={table.getPageCount()}
            />
            <span className="text-sm text-gray-700">of {table.getPageCount()}</span>
          </div>

          <button
            onClick={() => table.nextPage()}
            disabled={!table.getCanNextPage()}
            className="p-2 border border-gray-300 rounded disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
          >
            <ChevronRightIcon className="w-4 h-4" />
          </button>

          <button
            onClick={() => table.setPageIndex(table.getPageCount() - 1)}
            disabled={!table.getCanNextPage()}
            className="p-2 border border-gray-300 rounded disabled:opacity-50 disabled:cursor-not-allowed hover:bg-gray-50"
          >
            <ChevronDoubleRightIcon className="w-4 h-4" />
          </button>
        </div>
      </div>
    </div>
  );
}

getCanPreviousPage() and getCanNextPage() disable the buttons at the edges. The page number field subtracts 1, because the user counts from one and the table from zero.

Row selection

Selection adds a column of checkboxes. The columnHelper.display method creates a column with no data field, perfect for checkboxes and action buttons:

// components/SelectableUsersTable.tsx
'use client';

import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  useReactTable,
  RowSelectionState,
} from '@tanstack/react-table';
import { useState } from 'react';
import { TrashIcon, UserGroupIcon } from '@heroicons/react/24/outline';
import { User } from '@/types/User';

const columnHelper = createColumnHelper<User>();

interface SelectableUsersTableProps {
  data: User[];
  onDeleteSelected?: (selectedUsers: User[]) => void;
  onBulkAction?: (action: string, selectedUsers: User[]) => void;
}

export default function SelectableUsersTable({
  data,
  onDeleteSelected,
  onBulkAction
}: SelectableUsersTableProps) {
  const [rowSelection, setRowSelection] = useState<RowSelectionState>({});

  const columns = [
    // Selection column
    columnHelper.display({
      id: 'select',
      header: ({ table }) => (
        <input
          type="checkbox"
          checked={table.getIsAllRowsSelected()}
          onChange={table.getToggleAllRowsSelectedHandler()}
          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
        />
      ),
      cell: ({ row }) => (
        <input
          type="checkbox"
          checked={row.getIsSelected()}
          onChange={row.getToggleSelectedHandler()}
          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
        />
      ),
    }),
    columnHelper.accessor('name', {
      header: 'Username',
    }),
    columnHelper.accessor('email', {
      header: 'Email',
    }),
    columnHelper.accessor('role', {
      header: 'Role',
    }),
    columnHelper.accessor('status', {
      header: 'Status',
    }),
    // Actions column
    columnHelper.display({
      id: 'actions',
      header: 'Actions',
      cell: ({ row }) => (
        <div className="flex space-x-2">
          <button
            onClick={() => console.log('Edit user:', row.original)}
            className="text-blue-600 hover:text-blue-800 text-sm"
          >
            Edit
          </button>
          <button
            onClick={() => console.log('Delete user:', row.original)}
            className="text-red-600 hover:text-red-800 text-sm"
          >
            Remove
          </button>
        </div>
      ),
    }),
  ];

  const table = useReactTable({
    data,
    columns,
    state: {
      rowSelection,
    },
    onRowSelectionChange: setRowSelection,
    getCoreRowModel: getCoreRowModel(),
    enableRowSelection: true,
  });

  const selectedUsers = table.getFilteredSelectedRowModel().rows.map(row => row.original);

The RowSelectionState state is an object keyed by row id. The columns are defined inside the component here, so it is worth wrapping them in useMemo, as the best practices at the end of the lesson explain.

The bulk actions bar appears only when something is selected:

  return (
    <div className="space-y-4">
      {/* Bulk Actions */}
      {Object.keys(rowSelection).length > 0 && (
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-2">
              <UserGroupIcon className="w-5 h-5 text-blue-600" />
              <span className="text-sm font-medium text-blue-900">
                Selected {selectedUsers.length} users
              </span>
            </div>

            <div className="flex space-x-2">
              <button
                onClick={() => onBulkAction?.('activate', selectedUsers)}
                className="px-3 py-1 bg-green-600 text-white text-sm rounded hover:bg-green-700"
              >
                Activate
              </button>
              <button
                onClick={() => onBulkAction?.('deactivate', selectedUsers)}
                className="px-3 py-1 bg-yellow-600 text-white text-sm rounded hover:bg-yellow-700"
              >
                Deactivate
              </button>
              <button
                onClick={() => onDeleteSelected?.(selectedUsers)}
                className="px-3 py-1 bg-red-600 text-white text-sm rounded hover:bg-red-700 flex items-center space-x-1"
              >
                <TrashIcon className="w-4 h-4" />
                <span>Remove</span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Table */}
      <div className="overflow-x-auto">
        <table className="min-w-full bg-white border border-gray-200">
          <thead className="bg-gray-50">
            {table.getHeaderGroups().map((headerGroup) => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <th
                    key={header.id}
                    className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    {flexRender(header.column.columnDef.header, header.getContext())}
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {table.getRowModel().rows.map((row) => (
              <tr
                key={row.id}
                className={`hover:bg-gray-50 ${row.getIsSelected() ? 'bg-blue-50' : ''}`}
              >
                {row.getVisibleCells().map((cell) => (
                  <td key={cell.id} className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

getFilteredSelectedRowModel() returns the selected rows, and row.original is the original User object. The table does not delete data itself, it passes it to functions from props.

Server-side data fetching

With tens of thousands of records we move sorting and filtering to the server. The order is fixed: an API endpoint, manual sorting and filter state in the table, processing on the server and handling the response in the component. TanStack Query fetches the data:

// hooks/useUsersData.ts
import { useQuery, keepPreviousData } from '@tanstack/react-query';
import { useState } from 'react';

interface UseUsersDataParams {
  page: number;
  pageSize: number;
  sorting?: Array<{ id: string; desc: boolean }>;
  filters?: Array<{ id: string; value: any }>;
  globalFilter?: string;
}

interface UsersResponse {
  data: User[];
  totalCount: number;
  pageCount: number;
}

export function useUsersData(params: UseUsersDataParams) {
  return useQuery({
    queryKey: ['users', params],
    queryFn: async (): Promise<UsersResponse> => {
      const searchParams = new URLSearchParams({
        page: params.page.toString(),
        pageSize: params.pageSize.toString(),
        ...(params.globalFilter && { search: params.globalFilter }),
        ...(params.sorting?.length && {
          sort: JSON.stringify(params.sorting)
        }),
        ...(params.filters?.length && {
          filters: JSON.stringify(params.filters)
        }),
      });

      const response = await fetch(`/api/users?${searchParams}`);

      if (!response.ok) {
        throw new Error('Failed to fetch users');
      }

      return response.json();
    },
    placeholderData: keepPreviousData,
  });
}

queryKey contains the parameters, so every page or sorting change fetches new data. placeholderData: keepPreviousData is the TanStack Query 5 form that shows the previous page until the new one arrives, the older keepPreviousData: true option no longer works.

The component passes the table state to the hook and turns on manual mode with the manualPagination, manualSorting and manualFiltering flags:

// components/ServerSideUsersTable.tsx
'use client';

import {
  createColumnHelper,
  flexRender,
  getCoreRowModel,
  useReactTable,
  PaginationState,
  SortingState,
  ColumnFiltersState,
} from '@tanstack/react-table';
import { useState } from 'react';
import { useUsersData } from '@/hooks/useUsersData';
import { User } from '@/types/User';

const columnHelper = createColumnHelper<User>();

const columns = [
  columnHelper.accessor('name', {
    header: 'Username',
    enableSorting: true,
  }),
  columnHelper.accessor('email', {
    header: 'Email',
    enableSorting: true,
  }),
  columnHelper.accessor('role', {
    header: 'Role',
    enableSorting: true,
  }),
  columnHelper.accessor('status', {
    header: 'Status',
    enableSorting: true,
  }),
  columnHelper.accessor('createdAt', {
    header: 'Created at',
    enableSorting: true,
    cell: (info) => new Date(info.getValue()).toLocaleDateString('en-US'),
  }),
];

export default function ServerSideUsersTable() {
  const [pagination, setPagination] = useState<PaginationState>({
    pageIndex: 0,
    pageSize: 10,
  });
  const [sorting, setSorting] = useState<SortingState>([]);
  const [columnFilters, setColumnFilters] = useState<ColumnFiltersState>([]);
  const [globalFilter, setGlobalFilter] = useState('');

  const { data, isLoading, error } = useUsersData({
    page: pagination.pageIndex,
    pageSize: pagination.pageSize,
    sorting,
    filters: columnFilters,
    globalFilter,
  });

  const table = useReactTable({
    data: data?.data ?? [],
    columns,
    pageCount: data?.pageCount ?? -1,
    state: {
      pagination,
      sorting,
      columnFilters,
      globalFilter,
    },
    onPaginationChange: setPagination,
    onSortingChange: setSorting,
    onColumnFiltersChange: setColumnFilters,
    onGlobalFilterChange: setGlobalFilter,
    getCoreRowModel: getCoreRowModel(),
    manualPagination: true,
    manualSorting: true,
    manualFiltering: true,
  });

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center text-red-600 p-8">
        An error occurred while loading data
      </div>
    );
  }

In manual mode the table does not sort or filter by itself, it only reports state changes. pageCount comes from the server, because only the server knows the total number of records.

The view looks almost the same as in the client version:

  return (
    <div className="space-y-4">
      {/* Search */}
      <div className="flex items-center space-x-4">
        <input
          value={globalFilter ?? ''}
          onChange={(e) => setGlobalFilter(e.target.value)}
          className="px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500 flex-1 max-w-sm"
        />
      </div>

      {/* Table */}
      <div className="overflow-x-auto">
        <table className="min-w-full bg-white border border-gray-200">
          <thead className="bg-gray-50">
            {table.getHeaderGroups().map((headerGroup) => (
              <tr key={headerGroup.id}>
                {headerGroup.headers.map((header) => (
                  <th
                    key={header.id}
                    className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
                  >
                    <div
                      className={
                        header.column.getCanSort()
                          ? 'flex items-center cursor-pointer select-none hover:text-gray-700'
                          : ''
                      }
                      onClick={header.column.getToggleSortingHandler()}
                    >
                      {flexRender(header.column.columnDef.header, header.getContext())}
                    </div>
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody className="bg-white divide-y divide-gray-200">
            {table.getRowModel().rows.map((row) => (
              <tr key={row.id} className="hover:bg-gray-50">
                {row.getVisibleCells().map((cell) => (
                  <td key={cell.id} className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>

      {/* Pagination */}
      <div className="flex items-center justify-between">
        <div className="text-sm text-gray-700">
          Showing {data?.data.length ?? 0} of {data?.totalCount ?? 0} users
        </div>

        <div className="flex items-center space-x-2">
          <button
            onClick={() => table.setPageIndex(0)}
            disabled={!table.getCanPreviousPage()}
            className="px-3 py-1 border border-gray-300 rounded disabled:opacity-50"
          >
            First
          </button>

          <button
            onClick={() => table.previousPage()}
            disabled={!table.getCanPreviousPage()}
            className="px-3 py-1 border border-gray-300 rounded disabled:opacity-50"
          >
            Previous
          </button>

          <span className="text-sm">
            Page {table.getState().pagination.pageIndex + 1} of{' '}
            {table.getPageCount()}
          </span>

          <button
            onClick={() => table.nextPage()}
            disabled={!table.getCanNextPage()}
            className="px-3 py-1 border border-gray-300 rounded disabled:opacity-50"
          >
            Next
          </button>

          <button
            onClick={() => table.setPageIndex(table.getPageCount() - 1)}
            disabled={!table.getCanNextPage()}
            className="px-3 py-1 border border-gray-300 rounded disabled:opacity-50"
          >
            Last
          </button>
        </div>
      </div>
    </div>
  );
}

The difference is invisible to the user: every page click sends a new request to the API.

API Routes for a server-side table

On the server, a Route Handler reads the parameters from searchParams and does the same work the library did before:

// app/api/users/route.ts
import { NextRequest, NextResponse } from 'next/server';
import { User } from '@/types/User';

// Simulated data
const mockUsers: User[] = [
  // ... user data
];

export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;

  const page = parseInt(searchParams.get('page') || '0');
  const pageSize = parseInt(searchParams.get('pageSize') || '10');
  const search = searchParams.get('search') || '';
  const sortParam = searchParams.get('sort');
  const filtersParam = searchParams.get('filters');

  let filteredUsers = [...mockUsers];

  // Global search
  if (search) {
    filteredUsers = filteredUsers.filter(user =>
      user.name.toLowerCase().includes(search.toLowerCase()) ||
      user.email.toLowerCase().includes(search.toLowerCase()) ||
      user.role.toLowerCase().includes(search.toLowerCase())
    );
  }

  // Column filters
  if (filtersParam) {
    const filters = JSON.parse(filtersParam);
    filters.forEach((filter: { id: string; value: any }) => {
      filteredUsers = filteredUsers.filter(user => {
        const value = user[filter.id as keyof User];
        return value === filter.value;
      });
    });
  }

  // Sorting
  if (sortParam) {
    const sorting = JSON.parse(sortParam);
    sorting.forEach((sort: { id: string; desc: boolean }) => {
      filteredUsers.sort((a, b) => {
        const aVal = a[sort.id as keyof User];
        const bVal = b[sort.id as keyof User];

        if (aVal < bVal) return sort.desc ? 1 : -1;
        if (aVal > bVal) return sort.desc ? -1 : 1;
        return 0;
      });
    });
  }

  // Pagination
  const totalCount = filteredUsers.length;
  const pageCount = Math.ceil(totalCount / pageSize);
  const startIndex = page * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedUsers = filteredUsers.slice(startIndex, endIndex);

  return NextResponse.json({
    data: paginatedUsers,
    totalCount,
    pageCount,
  });
}

In order: search, column filters, sorting and cutting out the page. In a real application a database would do these steps with a query using WHERE, ORDER BY and LIMIT.

Responsive tables

A wide table does not fit on a phone. This component shows the table from the md breakpoint up, and on smaller screens cards with expandable details:

// components/ResponsiveUsersTable.tsx
'use client';

import { useState } from 'react';
import { User } from '@/types/User';

interface ResponsiveUsersTableProps {
  data: User[];
}

export default function ResponsiveUsersTable({ data }: ResponsiveUsersTableProps) {
  const [expandedRows, setExpandedRows] = useState<Set<string>>(new Set());

  const toggleRow = (userId: string) => {
    const newExpanded = new Set(expandedRows);
    if (newExpanded.has(userId)) {
      newExpanded.delete(userId);
    } else {
      newExpanded.add(userId);
    }
    setExpandedRows(newExpanded);
  };

  return (
    <div className="w-full">
      {/* Desktop Table */}
      <div className="hidden md:block overflow-x-auto">
        <table className="min-w-full bg-white border border-gray-200">
          {/* Standard desktop table */}
        </table>
      </div>

      {/* Mobile Cards */}
      <div className="md:hidden space-y-4">
        {data.map((user) => (
          <div key={user.id} className="bg-white border border-gray-200 rounded-lg shadow">
            <div className="p-4">
              <div className="flex items-center justify-between">
                <div className="flex-1">
                  <h3 className="font-medium text-gray-900">{user.name}</h3>
                  <p className="text-sm text-gray-600">{user.email}</p>
                </div>

                <button
                  onClick={() => toggleRow(user.id)}
                  className="ml-4 text-blue-600 text-sm"
                >
                  {expandedRows.has(user.id) ? 'Less' : 'More'}
                </button>
              </div>

              {expandedRows.has(user.id) && (
                <div className="mt-4 pt-4 border-t border-gray-200">
                  <div className="grid grid-cols-2 gap-4 text-sm">
                    <div>
                      <span className="font-medium text-gray-700">Role:</span>
                      <span className="ml-1">{user.role}</span>
                    </div>
                    <div>
                      <span className="font-medium text-gray-700">Status:</span>
                      <span className="ml-1">{user.status}</span>
                    </div>
                    <div className="col-span-2">
                      <span className="font-medium text-gray-700">Created:</span>
                      <span className="ml-1">
                        {new Date(user.createdAt).toLocaleDateString('en-US')}
                      </span>
                    </div>
                  </div>
                </div>
              )}
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

The expansion state is a Set of ids. We create a new Set on every change instead of mutating the old one, so React notices the change.

Data export

Exporting to CSV and JSON needs no library. The hook creates the file as a Blob and downloads it through a temporary link:

// hooks/useTableExport.ts
import { User } from '@/types/User';

export function useTableExport() {
  const exportToCSV = (data: User[], filename = 'users.csv') => {
    const headers = ['ID', 'Name', 'Email', 'Role', 'Status', 'Created at'];
    const csvContent = [
      headers.join(','),
      ...data.map(user => [
        user.id,
        user.name,
        user.email,
        user.role,
        user.status,
        new Date(user.createdAt).toLocaleDateString('en-US')
      ].join(','))
    ].join('\n');

    const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  const exportToJSON = (data: User[], filename = 'users.json') => {
    const jsonContent = JSON.stringify(data, null, 2);
    const blob = new Blob([jsonContent], { type: 'application/json' });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  };

  return { exportToCSV, exportToJSON };
}

CSV rows are joined with a newline character. This simple export does not handle commas inside values, in production wrap such fields in quotes.

Best practices

1. Performance optimization

The table compares data and columns by reference, so new arrays on every render force a recalculation:

// Good - use memo for columns
const columns = useMemo(() => [
  // column definitions
], []);

// Good - memo for data
const data = useMemo(() => users, [users]);

useMemo keeps the same reference between renders until the dependencies change.

2. Accessibility

Headless means accessibility is up to you. Use real table elements and ARIA attributes:

// Good - aria labels
<table role="table" aria-label="Users table">
  <thead>
    <tr role="row">
      <th role="columnheader" aria-sort="ascending">
        Name
      </th>
    </tr>
  </thead>
</table>

aria-sort tells screen readers which column the data is sorted by and in which direction.

3. TypeScript integration

A column helper typed with your data gives you suggestions and checks field names:

// Good - strong typing
const columnHelper = createColumnHelper<User>();

const columns = [
  columnHelper.accessor('name', {
    // Full IntelliSense support
  }),
];

A typo in a field name is a compile error, not an empty column in production.

Summary

TanStack Table with Next.js is a powerful combination for building advanced tables:

  1. Headless UI - full control over styling
  2. TypeScript-first - type safety
  3. Feature-rich - sorting, filtering, pagination
  4. Performance - optimizations, with virtualization from TanStack Virtual
  5. Server-side support - ideal for large datasets

My advice: keep the logic on the client up to a few thousand rows, and above that switch to manual mode with an API. In the next lesson you will learn Typed Routes, which protect your links from typos.

Remember: TanStack Table is the computing engine of the table, and the look of every cell belongs to you.

Code for this lesson: App.tsx
import React, { useState, useMemo } from 'react';

interface User {
  id: number;
  name: string;
  email: string;
  role: 'admin' | 'user' | 'moderator';
  status: 'active' | 'inactive' | 'pending';
  lastLogin: string;
}

const mockUsers: User[] = [
  { id: 1, name: 'Jan Kowalski', email: 'jan@quantum.city', role: 'admin', status: 'active', lastLogin: '2025-03-01' },
  { id: 2, name: 'Anna Nowak', email: 'anna@quantum.city', role: 'moderator', status: 'active', lastLogin: '2025-02-28' },
  { id: 3, name: 'Piotr Wisniewski', email: 'piotr@quantum.city', role: 'user', status: 'pending', lastLogin: '2025-02-25' },
  { id: 4, name: 'Maria Zielinska', email: 'maria@quantum.city', role: 'user', status: 'active', lastLogin: '2025-03-02' },
  { id: 5, name: 'Tomasz Dabrowski', email: 'tomasz@quantum.city', role: 'moderator', status: 'inactive', lastLogin: '2025-01-15' },
  { id: 6, name: 'Katarzyna Lewandowska', email: 'kasia@quantum.city', role: 'user', status: 'active', lastLogin: '2025-03-03' },
  { id: 7, name: 'Michal Wojcik', email: 'michal@quantum.city', role: 'admin', status: 'active', lastLogin: '2025-03-02' },
  { id: 8, name: 'Agnieszka Kaminska', email: 'aga@quantum.city', role: 'user', status: 'pending', lastLogin: '2025-02-20' },
  { id: 9, name: 'Robert Szymanski', email: 'robert@quantum.city', role: 'user', status: 'inactive', lastLogin: '2024-12-01' },
  { id: 10, name: 'Ewa Wozniak', email: 'ewa@quantum.city', role: 'moderator', status: 'active', lastLogin: '2025-03-01' },
];

type SortDir = 'asc' | 'desc' | null;

const statusColors: Record<string, string> = { active: '#4caf50', inactive: '#f44336', pending: '#ff9800' };
const roleColors: Record<string, string> = { admin: '#7c4dff', moderator: '#64ffda', user: '#888' };

const TanStackTableDemo = () => {
  const [data] = useState<User[]>(mockUsers);
  const [sortKey, setSortKey] = useState<keyof User | null>(null);
  const [sortDir, setSortDir] = useState<SortDir>(null);
  const [searchQuery, setSearchQuery] = useState('');
  const [roleFilter, setRoleFilter] = useState<string>('all');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [page, setPage] = useState(0);
  const pageSize = 5;

  const handleSort = (key: keyof User) => {
    if (sortKey === key) {
      setSortDir(prev => prev === 'asc' ? 'desc' : prev === 'desc' ? null : 'asc');
      if (sortDir === 'desc') setSortKey(null);
    } else {
      setSortKey(key);
      setSortDir('asc');
    }
  };

  const filtered = useMemo(() => {
    let result = [...data];
    if (searchQuery) result = result.filter(u => u.name.toLowerCase().includes(searchQuery.toLowerCase()) || u.email.toLowerCase().includes(searchQuery.toLowerCase()));
    if (roleFilter !== 'all') result = result.filter(u => u.role === roleFilter);
    if (statusFilter !== 'all') result = result.filter(u => u.status === statusFilter);
    if (sortKey && sortDir) {
      result.sort((a, b) => {
        const va = a[sortKey], vb = b[sortKey];
        const cmp = String(va).localeCompare(String(vb));
        return sortDir === 'asc' ? cmp : -cmp;
      });
    }
    return result;
  }, [data, searchQuery, roleFilter, statusFilter, sortKey, sortDir]);

  const paged = filtered.slice(page * pageSize, (page + 1) * pageSize);
  const totalPages = Math.ceil(filtered.length / pageSize);

  const sortIcon = (key: keyof User) => {
    if (sortKey !== key) return ' ↕';
    return sortDir === 'asc' ? ' ↑' : ' ↓';
  };

  return (
    <div style={{ background: '#0f0f23', minHeight: '100vh', padding: '20px', color: '#fff', fontFamily: 'sans-serif' }}>
      <h1 style={{ color: '#64ffda', textAlign: 'center' }}>Next.js + TanStack Table</h1>
      <p style={{ textAlign: 'center', color: '#888', marginBottom: '20px' }}>Sorting, Filtering, Pagination</p>

      <div style={{ maxWidth: '900px', margin: '0 auto' }}>
        <div style={{ display: 'flex', gap: '8px', marginBottom: '16px', flexWrap: 'wrap' }}>
          <input value={searchQuery} onChange={e => { setSearchQuery(e.target.value); setPage(0); }} placeholder="Search by name or email..."
            style={{ flex: 1, minWidth: '200px', padding: '10px', background: '#16213e', border: '1px solid #444', borderRadius: '6px', color: '#fff' }} />
          <select value={roleFilter} onChange={e => { setRoleFilter(e.target.value); setPage(0); }}
            style={{ padding: '10px', background: '#16213e', border: '1px solid #444', borderRadius: '6px', color: '#fff' }}>
            <option value="all">All Roles</option>
            <option value="admin">Admin</option>
            <option value="moderator">Moderator</option>
            <option value="user">User</option>
          </select>
          <select value={statusFilter} onChange={e => { setStatusFilter(e.target.value); setPage(0); }}
            style={{ padding: '10px', background: '#16213e', border: '1px solid #444', borderRadius: '6px', color: '#fff' }}>
            <option value="all">All Statuses</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
            <option value="pending">Pending</option>
          </select>
        </div>

        <div style={{ overflowX: 'auto', borderRadius: '10px', border: '1px solid #333' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr style={{ background: '#1a1a2e' }}>
                {[
                  { key: 'name' as keyof User, label: 'Name' },
                  { key: 'email' as keyof User, label: 'Email' },
                  { key: 'role' as keyof User, label: 'Role' },
                  { key: 'status' as keyof User, label: 'Status' },
                  { key: 'lastLogin' as keyof User, label: 'Last Login' },
                ].map(col => (
                  <th key={col.key} onClick={() => handleSort(col.key)}
                    style={{ padding: '12px', textAlign: 'left', color: '#64ffda', cursor: 'pointer', borderBottom: '2px solid #333', userSelect: 'none', whiteSpace: 'nowrap' }}>
                    {col.label}{sortIcon(col.key)}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {paged.map(user => (
                <tr key={user.id} style={{ borderBottom: '1px solid #1a1a2e' }}>
                  <td style={{ padding: '10px 12px' }}>{user.name}</td>
                  <td style={{ padding: '10px 12px', color: '#7c4dff' }}>{user.email}</td>
                  <td style={{ padding: '10px 12px' }}>
                    <span style={{ background: roleColors[user.role] + '33', color: roleColors[user.role], padding: '3px 10px', borderRadius: '12px', fontSize: '12px' }}>{user.role}</span>
                  </td>
                  <td style={{ padding: '10px 12px' }}>
                    <span style={{ color: statusColors[user.status], fontWeight: 'bold', fontSize: '13px' }}>{user.status}</span>
                  </td>
                  <td style={{ padding: '10px 12px', color: '#888' }}>{user.lastLogin}</td>
                </tr>
              ))}
              {paged.length === 0 && (
                <tr><td colSpan={5} style={{ textAlign: 'center', padding: '30px', color: '#555' }}>No results found</td></tr>
              )}
            </tbody>
          </table>
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: '12px' }}>
          <span style={{ color: '#888', fontSize: '13px' }}>Showing {paged.length} of {filtered.length} users</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button onClick={() => setPage(p => Math.max(0, p - 1))} disabled={page === 0}
              style={{ padding: '6px 12px', background: page === 0 ? '#222' : '#7c4dff', border: 'none', borderRadius: '4px', color: '#fff', cursor: page === 0 ? 'default' : 'pointer' }}>Prev</button>
            <span style={{ padding: '6px 12px', color: '#888' }}>{page + 1} / {totalPages || 1}</span>
            <button onClick={() => setPage(p => Math.min(totalPages - 1, p + 1))} disabled={page >= totalPages - 1}
              style={{ padding: '6px 12px', background: page >= totalPages - 1 ? '#222' : '#7c4dff', border: 'none', borderRadius: '4px', color: '#fff', cursor: page >= totalPages - 1 ? 'default' : 'pointer' }}>Next</button>
          </div>
        </div>
      </div>
    </div>
  );
};

export default TanStackTableDemo;

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. TanStack Table offers:

  2. 2. Which feature is NOT built into TanStack Table?

Hands-on tasks in the game

  • Code editor

    Implement a data table with sorting and filtering using TanStack Table

  • Code editor

    Create a table with columns and a data source.

  1. QuestionTanStack Table
  2. QuestionTanStack Table Features
  3. Coding taskPractice: Data Table with TanStack Table
  4. Coding taskTanStack Table Setup

Useful articles