How to Implement Default React Table Sort Functionality for a Specific Column on Mount

Seed the initialState.sorting array in useReactTable with a SortingState object containing the column id and desc boolean to render pre-sorted data immediately when the component mounts.

Default react table sort functionality eliminates the need for manual sorting logic or useEffect hooks when initializing TanStack React Table components. By leveraging the initialState parameter in the useReactTable hook, you can configure the table to display data in a specific sort order from the first render. This approach works within the facebook/react repository architecture by merging initial state into the internal table state before the sorting plugin processes the row model.

Understanding the Sorting Architecture

The TanStack React Table library implements sorting through a pipeline that processes state during the initial mount cycle. In packages/react/src/react-table/useReactTable.ts, the hook merges options.initialState into a fresh internal state before constructing the sorting plugin pipeline.

The core files involved in this process include:

When useReactTable executes, it calls createTableInstance(options), which immediately runs getSortedRowModel using the initial sorting data. This ensures the first render already contains rows in the desired order.

Step-by-Step Implementation

Define Stable Column IDs

Each column requires a stable id property to identify it within the sorting state. The id serves as the reference key in the SortingState array.

const columns: ColumnDef<Person>[] = [
  {
    accessorKey: 'firstName',
    header: 'First Name',
    id: 'firstName', // Explicit ID required for sorting reference
  },
  {
    accessorKey: 'age',
    header: 'Age',
    id: 'age',
  },
];

Configure the Initial Sorting State

Create a SortingState array that specifies which columns to sort and in which direction. Set desc: false for ascending order or desc: true for descending.

import { SortingState } from '@tanstack/react-table';

const defaultSorting: SortingState = [
  { id: 'age', desc: false }, // Sort by age ascending on mount
];

Register the Sorting Plugin

Pass the defaultSorting array to initialState.sorting and include getSortedRowModel in the table options. Without getSortedRowModel, the sorting state would be ignored.

const table = useReactTable({
  data,
  columns,
  getCoreRowModel: getCoreRowModel(),
  getSortedRowModel: getSortedRowModel(),
  initialState: {
    sorting: defaultSorting,
  },
});

Complete Implementation Example

The following example demonstrates a fully configured table that sorts by the age column in ascending order immediately upon mounting:

import React from 'react';
import {
  ColumnDef,
  getCoreRowModel,
  getSortedRowModel,
  flexRender,
  useReactTable,
  SortingState,
} from '@tanstack/react-table';

type Person = {
  firstName: string;
  lastName: string;
  age: number;
};

const columns: ColumnDef<Person>[] = [
  {
    accessorKey: 'firstName',
    header: 'First Name',
    id: 'firstName',
  },
  {
    accessorKey: 'lastName',
    header: 'Last Name',
    id: 'lastName',
  },
  {
    accessorKey: 'age',
    header: 'Age',
    id: 'age',
  },
];

const data: Person[] = [
  { firstName: 'Alice', lastName: 'Zephyr', age: 34 },
  { firstName: 'Bob', lastName: 'Yellow', age: 27 },
  { firstName: 'Cara', lastName: 'Xavier', age: 45 },
];

const defaultSorting: SortingState = [{ id: 'age', desc: false }];

export function PeopleTable() {
  const table = useReactTable({
    data,
    columns,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    initialState: {
      sorting: defaultSorting,
    },
  });

  return (
    <table>
      <thead>
        {table.getHeaderGroups().map(headerGroup => (
          <tr key={headerGroup.id}>
            {headerGroup.headers.map(header => (
              <th key={header.id}>
                {flexRender(header.column.columnDef.header, header.getContext())}
              </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>
  );
}

The table.getRowModel().rows property already reflects the sorted order on the first render because getSortedRowModel processes the initialState.sorting configuration during the initial state merge in useReactTable.

Advanced Patterns

Controlled Sorting State

To allow users to change the sort order after mount while maintaining the default initially, use React state and the onSortingChange callback:

const [sorting, setSorting] = React.useState<SortingState>(defaultSorting);

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

Multi-Column Default Sort

Sort by multiple columns hierarchically by including multiple entries in the defaultSorting array:

const defaultSorting: SortingState = [
  { id: 'lastName', desc: false }, // Primary: alphabetical by last name
  { id: 'age', desc: true },      // Secondary: age descending
];

The table applies these sorts in array order, using subsequent columns as tie-breakers for preceding ones.

Summary

  • Default react table sort functionality relies on the initialState.sorting property in useReactTable options.
  • Each sorting entry requires a column id (matching the ColumnDef id) and a desc boolean for direction.
  • The getSortedRowModel plugin must be registered to process the sorting state.
  • File paths packages/react/src/react-table/useReactTable.ts and packages/react/src/react-table/getSortedRowModel.ts handle the state merging and row ordering logic.
  • No useEffect or manual sorting logic is required—the table initializes with sorted data on the first render.

Frequently Asked Questions

How do I change the default sort direction from ascending to descending?

Set the desc property to true in your SortingState entry. For example: { id: 'age', desc: true } sorts the age column in descending order (highest to lowest) when the component mounts.

Can I set a default sort on a column that uses a custom accessor function?

Yes, provided you explicitly define an id property in the column definition. Columns with accessor functions require manual id assignment because the library cannot automatically generate stable identifiers from function references.

What happens if I omit the getSortedRowModel plugin?

The table will ignore the sorting state entirely, including initialState.sorting, and render rows in their original data order. The getSortedRowModel function in packages/react/src/react-table/getSortedRowModel.ts contains the logic that actually reorders rows based on the current sorting configuration.

Is it possible to combine default sorting with other initial state options?

Yes, initialState accepts multiple configuration objects simultaneously. You can combine sorting with pagination, columnVisibility, and other state slices in the same initialState object passed to useReactTable.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →