Capítulo 1 de 24

Chapter 1: Quickstart (File-Based Routing)

Core Idea

This example is the minimal starting point for TanStack Router using file-based routing: routes are files under src/routes, and a code generator (@tanstack/router-plugin) builds routeTree.gen.ts automatically. It exists to show the smallest possible app shape a new project should copy.

Setup

  • Routing style: file-based
  • Key dependencies: @tanstack/react-router, @tanstack/router-plugin (Vite plugin that watches src/routes and generates the route tree), @tanstack/react-router-devtools, zod, redaxios
  • Structure: src/main.tsx creates the router from the generated routeTree.gen.ts and renders RouterProvider. src/routes/__root.tsx defines the root layout with navigation. src/routes/about.tsx is a leaf route file matched to /about.

Code Example

// src/main.tsx
import { RouterProvider, createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'

const router = createRouter({
  routeTree,
  defaultPreload: 'intent',
  scrollRestoration: true,
})

declare module '@tanstack/react-router' {
  interface Register {
    router: typeof router
  }
}
// src/routes/about.tsx
import { createFileRoute } from '@tanstack/react-router'

export const Route = createFileRoute('/about')({
  component: AboutComponent,
})

function AboutComponent() {
  return (
    <div className="p-2">
      <h3>About</h3>
    </div>
  )
}
  • What it demonstrates: createFileRoute(path) ties a file to a URL path and exports a Route object; the generated routeTree.gen.ts is the single source of truth the router consumes, and declare module registers the router instance for full type inference across the app.

Key Takeaways

  1. File-based routing is the recommended default for new TanStack Router projects: adding a route is adding a file, no manual tree wiring.
  2. The Register interface declaration is what gives Link to="..." and useParams() their type safety; it must point at the actual router instance created in main.tsx.
  3. defaultPreload: 'intent' (hover/focus preloading) and scrollRestoration: true are sane defaults worth carrying into any new project.

Connects To

  • ch002-quickstart (code-based): the exact same app (Home/About), but routes are declared inline with createRoute and stitched together with addChildren instead of being generated from files. Compare the two to decide which routing style fits a project.