Skip to content

Why TanStack Router?

For our Task Manager application, we are using TanStack Router. It is a powerful, type-safe router for React applications.

TanStack Router provides 100% type safety. This means TypeScript will catch errors if you try to navigate to a route that doesn’t exist or forget a required parameter.

It treats search parameters (URL query strings) as first-class citizens. They are validated, typed, and managed just like other state.

It supports features like data loading, caching, and pending states out of the box.

To get started with TanStack Router, install the necessary packages in your project:

Terminal window
bun add @tanstack/react-router @tanstack/react-router-devtools
bun add -D @tanstack/router-plugin
  • @tanstack/react-router: The core router library for React
  • @tanstack/react-router-devtools: Development tools for debugging routes
  • @tanstack/router-plugin: Vite plugin for automatic route generation

In our Task Manager project, these packages are already installed, but you’ll need to run these commands when starting a new project.

The router is the core of the application’s navigation. In our tm project, this is set up in src/react-app/main.tsx.

import { RouterProvider, createRouter } from "@tanstack/react-router";
import { routeTree } from "./routeTree.gen";
const router = createRouter({ routeTree });
// Register the router instance for type safety
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}

We use file-based routing. The file structure in src/routes determines the URL paths.

  • routes/index.tsx -> /
  • routes/about.tsx -> /about
  • routes/tasks/$taskId.tsx -> /tasks/123

To create a new route, follow these steps:

  1. Go to the src/routes folder in your project.

  2. Create a new file called about.tsx.

  3. Add this code to the file:

import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/about')({
component: About,
})
function About() {
return (
<div>
<h1>About Our App</h1>
<p>This is a fun task manager app made with love!</p>
</div>
)
}

This defines a route for the /about URL that renders the About component. The createFileRoute('/about') connects the file name to the route path.

Layouts allow us to share UI (like a sidebar or header) across multiple routes.

In our project, we use:

  • _auth.tsx: Layout for login/signup pages (no sidebar).
  • _protected.tsx: Layout for the dashboard (includes Sidebar, Header).

The _ prefix creates a pathless layout route, meaning it wraps child routes without adding a segment to the URL.

TanStack Router automatically generates a routeTree.gen.ts file based on your file structure. You don’t need to manually maintain a list of routes!

// routeTree.gen.ts (Auto-generated)
import { Route as rootRoute } from "./routes/__root";
import { Route as IndexImport } from "./routes/index";
// ...

In the next section, we will put this into practice with an exercise.