Announcing nuqs version 2
nuqs
ParsersCommunity

TanStack Table Parsers

Store your table state in the URL, with style.

TanStack Table is a popular library for managing tabular content in React (and other frameworks).

By default, it will store its state in memory, losing all filters, sorts and pagination when the page is refreshed. This is a prime example where URL state shines.

Using URL state instead of in memory state requires providing the query state to the useReactTable hook and then hooking in to the onChange event to update query state.

For a complete example see sadmann7/shadcn-table

Pagination

TanStack Table stores pagination under two pieces of state:

  • pageIndex: a zero-based integer representing the current page
  • pageSize: an integer representing the number of items per page

Filtering

This section is empty for now, contributions are welcome!

Sorting

TanStack Table stores sorting in an an array of objects with keys:

  • id: a string with the column name
  • desc: a boolean indicating if the sorting is descending (true) or ascending (false)
import {useReactTable, type SortingState, type Updater} from "@tanstack/react-table"
import {useQueryState, parseAsJson} from 'nuqs'
import {z} from 'zod'
 
// sorting schema to pase to `parseAsJson`. Any validation solution will work
const sortingSchema = z.object({
  id: z.string(),
  desc: z.boolean(),
})
 
const [sorting, setSorting] = useQueryState("sort", parseAsJson(sortingSchema.parse))
 
// Handle on sort change callback from the table
function onSortingChange(updaterOrValue: Updater<SortingState>) {
  const newSorting = typeof updaterOrValue === "function" ? updaterOrValue(sorting) : updaterOrValue
  void setSorting(newSorting)
}
 
// Create the table with manually provided state and callback
const table = useReactTable({
  ...otherProps,
  onSortingChange,
  state: {
    ...otherState,
    sorting,
  }
})

On this page