Blog>
Snippets

Implementing Basic Sorting with TanStack Table

Demonstrates how to implement a simple column sorting feature using TanStack Table, including the necessary setup and configuration.
import { useTable, useSortBy } from '@tanstack/react-table';
Import useTable and useSortBy hooks from @tanstack/react-table.
const data = React.useMemo(() => [...], []);
Define your table data inside a useMemo hook for performance optimization.
const columns = React.useMemo(() => [
  {
    Header: 'Column Name',
    accessor: 'columnName', // accessor is the 'key' in the data
  },
  // Add more columns as needed
], []);
Define your table columns, including header names and accessors, inside a useMemo hook.
const tableInstance = useTable({ columns, data }, useSortBy);
Instantiate the table with useTable hook, passing columns and data. Include useSortBy to enable sorting.
const {
  getTableProps,
  getTableBodyProps,
  headerGroups,
  rows,
  prepareRow,
} = tableInstance;
Destructure table instance to get table utility methods and properties.
<table {...getTableProps()}>
  <thead>
    {/* Loop over the header rows */}
    {headerGroups.map(headerGroup => (
      <tr {...headerGroup.getHeaderGroupProps()}>
        {/* Loop over the headers in each row */}
        {headerGroup.headers.map(column => (
          <th {...column.getHeaderProps(column.getSortByToggleProps())}>{
            column.render('Header')
            /* Add a sort direction indicator */}
            <span>
              {column.isSorted
                ? column.isSortedDesc
                  ? ' 🔽'
                  : ' 🔼'
                : ''}
            </span>
          </th>
        ))}
      </tr>
    ))}
  </thead>
  <tbody {...getTableBodyProps()}>
    {/* Loop over the table rows */}
    {rows.map(row => {
      prepareRow(row);
      return (
        <tr {...row.getRowProps()}>
          {/* Loop over the cells in each row */}
          {row.cells.map(cell => {
            return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>;
          })}
        </tr>
      );
    })}
  </tbody>
</table>
Render the table structure with sorting enabled: headers will toggle sort direction on click.