TanStack Router logo

TanStack Router

A fully type-safe router for React that treats URL search parameters as first-class global state, featuring built-in data caching.

npm install @tanstack/react-router
12.4K1.2M/weekv1.139.111.93 MBMIT448 issues
Last updated: 2025-11-29
Star history chart for TanStack/router

TL;DR

A next-generation routing library built from the ground up for 100% TypeScript inference, eliminating broken links and missing parameters.

Combines routing with powerful data fetching (SWR-style caching) and state management, specifically designed to handle complex URL search parameters.

Why TanStack Router?

TanStack Router represents a paradigm shift in React routing. While traditional routers treat the URL as a simple string matcher, TanStack Router treats the URL as a state manager.

  • 100% Type Safety: It doesn't just check your syntax; it infers your entire route tree. If you try to link to a route that doesn't exist or forget a required parameter, your build will fail.
  • Search Params as State: Most routers treat query strings as second-class citizens. TanStack Router validates, parses, and types search parameters (JSON-serializable) automatically, making the URL a reliable source of truth for global state.
  • Built-in Data Caching: It includes a built-in caching layer (similar to TanStack Query) for route loaders. It handles stale-while-revalidate, background refetching, and preloading data on hover/intent.
  • File-Based Routing: It generates your route configuration from your file structure (similar to Next.js or Remix), ensuring your code and your router are always in sync.
  • Preloading: Instant navigation is achieved by preloading code and data when users hover over links, ensuring the next page is ready before they even click.

Code Snippet

The power of TanStack Router lies in its createFileRoute API, which enforces strict validation for both path parameters and search parameters (query strings).

import { createFileRoute } from '@tanstack/react-router'
import { z } from 'zod'

// 1. Define the search params schema (e.g., for pagination/filters)
const productSearchSchema = z.object({
  page: z.number().catch(1),
  filter: z.string().optional(),
})

export const Route = createFileRoute('/products/')({
  // 2. Validate Search Params: These are now fully typed in the component!
  validateSearch: (search) => productSearchSchema.parse(search),

  // 3. Loader: Built-in caching and data fetching
  loaderDeps: ({ search: { page, filter } }) => ({ page, filter }),
  loader: async ({ deps: { page, filter } }) => {
    return fetchProducts({ page, filter })
  },

  // 4. Component
  component: ProductList,
})

function ProductList() {
  const products = Route.useLoaderData()
  // 'page' and 'filter' are typed (number, string | undefined)
  const { page, filter } = Route.useSearch() 
  const navigate = Route.useNavigate()

  return (
    <div>
      {/* This Link is type-checked. Passing a string for 'page' would error. */}
      <button
        onClick={() =>
          navigate({
            search: (prev) => ({ ...prev, page: prev.page + 1 }),
          })
        }
      >
        Next Page
      </button>
    </div>
  )
}

Pros and Cons

TanStack Router offers unmatched developer experience (DX) for TypeScript teams, but it demands a shift in how you think about routing.

Pros

  • Confidence: The "Link" component is fully typed. Refactoring routes or changing parameter names becomes trivial because the compiler catches every usage.
  • State Management: By effectively managing search parameters, it removes the need for global stores (like Redux/Zustand) for things like filters, pagination, and sorting.
  • Developer Tools: It ships with a best-in-class DevTool that visualizes route matches, loader data, and search params in real-time.
  • Performance: Features like route masking and intent-based preloading make applications feel significantly snappier than traditional SPAs.

Cons

  • Codegen Dependency: It relies on a CLI process to generate the route tree type definitions. You need to run a "watcher" process during development.
  • Learning Curve: The heavy use of TypeScript generics and functional patterns can be intimidating for developers less comfortable with advanced TS.
  • Strictness: The rigid requirement for type safety means you cannot "hack" a navigation; you must strictly adhere to the schemas you defined.

Comparison with Other Routing Libraries

LibraryDesign PhilosophyBest ForPain Points
TanStack RouterType-Safety & State
The URL is the single source of truth; strict types everywhere.
Complex SaaS/Dashboards
Apps with heavy filtering, pagination, and complex URL state requirements.
Setup Complexity
Requires a build step/codegen watcher to function effectively.
React RouterStandards-Based
Focuses on web standards and stability; looser typing.
General Purpose
Teams wanting a familiar API and seamless migration to Remix.
Search Params DX
Handling complex query strings (parsing/serializing) requires manual work.
Next.js RouterFramework Integrated
Coupled tightly with the Next.js server/build infrastructure.
Next.js Apps
Server-side rendering and static site generation out of the box.
Vendor Lock-in
Cannot be used outside of the Next.js framework; limited client-side control.

Verdict: When to Adopt

Choose TanStack Router if you are building a Client-Side Rendering (CSR) application (SPA) and your team uses TypeScript. It is the superior choice for complex dashboards, admin panels, and data-heavy applications where maintaining URL state (filters, sorting) is critical.

If you are building a public-facing website that requires Server-Side Rendering (SSR) and SEO as a primary concern, you might prefer a meta-framework like Remix (React Router v7) or Next.js, although TanStack Router also supports SSR (via TanStack Start).