🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

React Data Tables: Sorting, Filtering, and Virtual Rows

React UIđŸŸĸ Free Lesson

What You'll Learn

  • 1Explain why sorting, filtering and pagination are stages of one pipeline rather than three features
  • 2Define column accessors and per-column sort functions once and reuse them across header and cell rendering
  • 3Decide between controlled and uncontrolled table state and keep page state consistent after a filter changes
  • 4Choose between pagination, windowing and server-side mode when the row count passes ten thousand

Most internal tools grow a table the same way. Someone maps an array over table markup, adds a click handler that flips a sort direction, then adds a slice for pagination. Two features later the table still behaves. The third feature is where it usually breaks, because sorting, filtering and paging are not three independent concerns — they are three stages of one pipeline, and ad-hoc state treats them as three separate families of bugs: the page number points past the end of a filtered result, the sort is applied before the search narrows the rows, a selected record vanishes the moment the data refetches. A headless table library does not draw anything for you. It owns the pipeline: given rows and a set of feature states, it computes the row model you should render, and you supply the markup.

What a headless table actually owns

TanStack Table knows nothing about CSS, markup or your design system. What it knows is the order operations must run in: column resolution, filtering, sorting, grouping, pagination, selection and expansion. Each feature can be uncontrolled, where the library keeps the state internally, or controlled, where you store it and pass it back on every render. That single distinction is what lets the same table component live in a URL-driven index where sort and page belong in the query string and in a modal where they are purely local.

Because the stages run in a fixed order, a search box and a sort header never need to know about each other. Filtering narrows the row set, sorting orders the survivors, pagination slices the result. Bugs that look mysterious usually turn out to be a feature wired into the wrong stage.

OrderStageWhat it producesState that drives it
1Column resolutionReads each accessor from a rowcolumn definitions
2FilteringDrops rows that fail a filterglobalFilter, columnFilters
3SortingOrders the surviving rowssorting
4GroupingCollapses rows into group headersgrouping, expanded
5PaginationSlices the final rows into one pagepagination
6SelectionTracks chosen row ids across pagesrowSelection

Selection sits last and is keyed by row id, which is why a selection survives paging as long as you give the table a stable getRowId. Pagination runs after filtering, which is why page three of a filtered list is not page three of the raw list. If a behaviour surprises you, check which stage you hooked into before you add state.

Column definitions are the contract

A column definition describes where a value comes from and how it renders, and nothing else. Accessor keys read flat fields, accessor functions compute values such as a full name, and a cell function formats for display without mutating the underlying row. Keeping formatting out of the data means the same rows can power a table, a CSV export and a chart without three copies of the transformation logic.

import { useMemo, useState } from 'react';
import {
  useReactTable,
  getCoreRowModel,
  getSortedRowModel,
  getFilteredRowModel,
  getPaginationRowModel,
  flexRender,
} from '@tanstack/react-table';

const columns = [
  {
    id: 'customer',
    accessorFn: (row) => `${row.firstName} ${row.lastName}`,
    header: 'Customer',
    cell: (info) => info.getValue(),
  },
  {
    accessorKey: 'mrr',
    header: 'MRR',
    cell: (info) =>
      new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: 'USD',
      }).format(info.getValue()),
    sortingFn: (a, b) => a.original.mrr - b.original.mrr,
  },
  {
    accessorKey: 'renewedAt',
    header: 'Renewed',
    cell: (info) => new Date(info.getValue()).toLocaleDateString(),
    sortingFn: 'datetime',
    sortDescFirst: false,
  },
];

Notice that currency formatting lives in the cell and numeric ordering lives in sortingFn. A string comparison would order nine thousand dollars above twelve thousand dollars, and a default lexicographic sort would order dates by their localised display text. Both are bugs the data does not announce.

Wiring state, rendering rows, and keeping the page legal

The table component below keeps sorting, filters and pagination in React state so the URL can own them later, and renders whatever row model the pipeline returns. The header cell reads the current sort direction for its accessible label, and the body renders only the current page.

export function CustomerTable({ rows }) {
  const [sorting, setSorting] = useState([]);
  const [filters, setFilters] = useState([]);
  const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 25 });

  const table = useReactTable({
    data: rows,
    columns,
    state: { sorting, columnFilters: filters, pagination },
    onSortingChange: setSorting,
    onColumnFiltersChange: setFilters,
    onPaginationChange: setPagination,
    getRowId: (row) => row.id,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getFilteredRowModel: getFilteredRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
  });

  const filter = table.getState().globalFilter || '';

  return (
    <div>
      <input
        value={filter}
        onChange={(event) => table.setGlobalFilter(event.target.value)}
        placeholder="Search customers"
        aria-label="Search customers"
      />
      <table>
        <thead>
          {table.getHeaderGroups().map((group) => (
            <tr key={group.id}>
              {group.headers.map((header) => (
                <th key={header.id}>
                  <button
                    type="button"
                    onClick={header.column.getToggleSortingHandler()}
                    aria-sort={header.column.getIsSorted() || 'none'}
                  >
                    {flexRender(header.column.columnDef.header, header.getContext())}
                    {header.column.getIsSorted() === 'asc' ? ' (ascending)' : ''}
                    {header.column.getIsSorted() === 'desc' ? ' (descending)' : ''}
                  </button>
                </th>
              ))}
            </tr>
          ))}
        </thead>
        <tbody>
          {table.getRowModel().rows.map((row) => (
            <tr key={row.id}>
              {row.getVisibleCells().map((cell) => (
                <td key={cell.id}>
                  {flexRender(cell.column.columnDef.cell, cell.getContext())}
                </td>
              ))}
            </tr>
          ))}
        </tbody>
      </table>
      <p>
        Page {table.getState().pagination.pageIndex + 1} of {Math.max(table.getPageCount(), 1)}
      </p>
      <button
        type="button"
        onClick={() => table.previousPage()}
        disabled={!table.getCanPreviousPage()}
      >
        Previous
      </button>
      <button
        type="button"
        onClick={() => table.nextPage()}
        disabled={!table.getCanNextPage()}
      >
        Next
      </button>
    </div>
  );
}

The one behaviour worth checking by hand: type a search that leaves two pages of results while you are viewing page five. Without an automatic page reset the table renders an empty body and a Next button that is disabled, which users read as data loss. Reset pageIndex whenever filters change, either through the library option or an effect, and clamp instead of trusting the previous value.

Filtering modes and how they differ

A global filter runs one predicate across every searchable column, which is what a single search box needs. Column filters attach to one column each, which is what a sidebar of facets needs. Faceted filters go further: they ask the table for the distinct values present in the filtered data so a dropdown can show counts, and those counts update as other filters apply. A custom filter function is a plain predicate over the row and the column value, so domain rules such as "renewed in the last quarter" stay in one place instead of leaking into the search box handler.

Debounce at the input, not in the table. The pipeline is synchronous and cheap compared with a network round trip, so when filtering hits a server the usual shape is a controlled table with manualFiltering enabled, a debounced query string, and a fetch that aborts the previous request. The table then receives only the rows for the current page and a total row count, and it calculates page bounds from that number instead of the array length.

Selection that survives paging and refetches

Row selection is a map from row id to boolean. Because it is keyed by id rather than by index, it survives sorting and paging for free, and it survives a refetch as long as ids are stable. The traps are the ones you would expect from any map: ids that are array positions silently select the wrong rows after a sort, and a filter that hides selected rows makes the header checkbox look inconsistent unless you decide explicitly whether it operates on visible rows or on all selected ids.

Give the table a getRowId derived from the record, keep selection state above the component that fetches, and treat "select all" as an operation over the current filtered row model rather than over the raw array. For really large selections, store ids in a Set outside React state and subscribe, because a fifty-thousand-entry object inside state will re-render on every keystroke.

Ten thousand rows without ten thousand DOM nodes

Pagination hides the cost of large data rather than removing it, and users increasingly expect to scroll. Windowing renders only the rows near the viewport, which keeps the DOM at a few dozen nodes regardless of row count. The virtualizer needs an estimated row height and, for variable rows, a measurement callback.

import { useVirtualizer } from '@tanstack/react-virtual';

export function VirtualRows({ rows, parentRef }) {
  const virtualizer = useVirtualizer({
    count: rows.length,
    getScrollElement: () => parentRef.current,
    estimateSize: () => 48,
    overscan: 8,
  });

  return (
    <div ref={parentRef} style={{ height: 600, overflow: 'auto' }}>
      <div style={{ height: virtualizer.getTotalSize(), position: 'relative' }}>
        {virtualizer.getVirtualItems().map((item) => {
          const row = rows[item.index];
          return (
            <div
              key={row.id}
              style={{
                position: 'absolute',
                top: 0,
                left: 0,
                width: '100%',
                height: item.size,
                transform: `translateY(${item.start}px)`,
              }}
            >
              {row.firstName} {row.lastName}
            </div>
          );
        })}
      </div>
    </div>
  );
}

Two costs arrive with windowing. Browser find-in-page stops working because the text is not in the document, and focus on a row can jump when a measurement changes above it. Both are solvable, but they are the reason to prefer pagination for record-keeping screens and windowing for exploratory ones.

ApproachBest forWeak spot
PaginationAudits, reports, anything cited by page numberKills quick scanning across a large set
WindowingLong exploratory lists with uniform row heightsFind-in-page and variable heights need care
Server-side modeData the client should never hold in fullEvery interaction costs a round trip
Grouped tree viewHierarchical records such as accounts and seatsMore state, harder keyboard navigation

When a table is the wrong shape

Three columns and twenty rows rarely justify this machinery, and neither does a screen whose rows are really cards with images, badges and actions. A table shines when values are comparable across rows and the user's task is scanning a column for an outlier. If the task is comparing two or three attributes of one record at a time, a list or a detail pane wins. Choosing late is cheap because the column definitions are portable — moving from a table to a list usually reuses the same accessors with different cell markup.

Common Mistakes

Sorting with the default string comparator on numbers or dates

Fix: Provide a sortingFn per column so numeric and temporal ordering is explicit

Leaving pageIndex unchanged after a filter removes the current page

Fix: Reset or clamp the page whenever the filtered row count changes

Using array index as the row id so selection drifts after a sort

Fix: Pass a stable getRowId that reads the record id from the data

Formatting values inside the data so exports and charts inherit display text

Fix: Keep raw values in the rows and format in the cell renderer only

Best Practices

  • Keep column definitions in a module so tables, exports and charts share one source of truth
  • Control table state when the URL or a saved view should reproduce the screen
  • Debounce search input and abort superseded requests when filtering hits a server
  • Announce sort direction with aria-sort and label every icon-only control
  • Measure before choosing between pagination and windowing; ten thousand rows paginate fine

Key Takeaways

  • A table is a pipeline: filter, then sort, then paginate, then select — order explains most surprising bugs
  • Column definitions own accessors, formatting and sort behaviour, so data stays raw and reusable
  • Page state must be reset or clamped when a filter shrinks the result set below the current page
  • Stable row ids are what make selection survive sorting, paging and refetches
  • Windowing trades DOM size for find-in-page and focus complexity; pick it for scanning, pagination for citation
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert React Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement