1---2name: tanstack-router3description: Type-safe, file-based React routing with route loaders, search params validation, code splitting, preloading, navigation, route context, and TanStack Query integration. Use when setting up file-based routing, adding search params validation, implementing route loaders, code splitting routes, configuring virtual file routes, protecting routes with auth guards, or fixing type registration errors. Use for router setup, navigation patterns, URL state management, data loading.4license: MIT5---6
7# TanStack Router
8
9Type-safe, file-based routing for React with route-level data loading, search params validation, code splitting, and TanStack Query integration.
10
11**Package:** `@tanstack/react-router` | **Plugin:** `@tanstack/router-plugin`
12
13## Quick Reference
14
15| Pattern | Usage |
16| --------------------------------- | --------------------------------------- |
17| `createFileRoute('/path')` | Define file-based route |
18| `createRootRouteWithContext<T>()` | Root route with typed context |
19| `createLazyFileRoute('/path')` | Code-split route component |
20| `zodValidator(schema)` | Search params validation |
21| `Route.useLoaderData()` | Access loader data in component |
22| `Route.useParams()` | Type-safe route params |
23| `Route.useSearch()` | Type-safe search params |
24| `useNavigate()` | Programmatic navigation |
25| `useBlocker()` | Block navigation (dirty forms) |
26| `notFound()` | Throw 404 from loader |
27| `getRouteApi('/path')` | Type-safe hooks in split files |
28| `stripSearchParams(defaults)` | Clean default values from URLs |
29| `retainSearchParams(['key'])` | Preserve params across navs |
30| `useAwaited({ promise })` | Suspend until deferred promise resolves |
31| `useCanGoBack()` | Check if router can go back safely |
32
33## Data Loading
34
35| Method | Returns | Throws | Use Case |
36| -------------------- | ------- | ------ | ------------------------------------------------ |
37| `ensureQueryData` | Data | Yes | Route loaders (recommended) |
38| `prefetchQuery` | void | No | Background prefetching |
39| `fetchQuery` | Data | Yes | Immediate data need |
40| `defer()` (optional) | Promise | No | Stream non-critical data (promises auto-handled) |
41
42## Preloading
43
44| Strategy | Behavior | Use Case |
45| ------------ | ------------------------- | --------------------------- |
46| `'intent'` | Preload on hover/focus | Default for most links |
47| `'render'` | Preload when Link mounts | Critical next pages |
48| `'viewport'` | Preload when Link in view | Below-fold content |
49| `false` | No preloading | Heavy, rarely-visited pages |
50
51## File Organization
52
53| File | Purpose |
54| -------------------- | ---------------------------- |
55| `__root.tsx` | Root route with `<Outlet />` |
56| `index.tsx` | Index route for `/` |
57| `posts.$postId.tsx` | Dynamic param route |
58| `_authenticated.tsx` | Pathless layout (auth guard) |
59| `dashboard.lazy.tsx` | Code-split component |
60
61## Common Mistakes
62
63| Mistake | Fix |
64| --------------------------------- | ----------------------------------------------------- |
65| Missing router type registration | Add `declare module` with `Register` interface |
66| `useParams()` without `from` | Always pass `from: '/route/path'` for exact types |
67| `useNavigate()` for regular links | Use `<Link>` for `<a>` tags, a11y, preloading |
68| `prefetchQuery` in loaders | Use `ensureQueryData` (returns data, throws errors) |
69| Fetching in `useEffect` | Use route loaders (prevents waterfalls) |
70| Sequential fetches in loader | Use `Promise.all` for parallel requests |
71| Missing leading slash | Always `'/about'` not `'about'` |
72| TanStackRouterVite after react() | Plugin MUST come before `react()` in Vite config |
73| `strict: false` params unparsed | Use strict mode or manually parse after navigation |
74| Pathless route notFoundComponent | Define `notFoundComponent` on child routes instead |
75| Aborted loader undefined error | Guard `errorComponent` with `if (!error) return null` |
76| No `loaderDeps` declared | Declare deps so loader only re-runs when they change |
77
78## Delegation
79
80- **TanStack Query patterns** — data fetching, caching, mutations: use `tanstack-query` skill
81- **TanStack Start** — server functions, SSR, server-side auth: use `tanstack-start` skill
82- **TanStack Table** — table rendering with router search params: use `tanstack-table` skill
83- **Router + Query integration** — loader data flow, preloading: see [Loader Data Flow Patterns](references/loader-query-patterns.md)
84
85> If the `tanstack-devtools` skill is available, delegate router state debugging and route tree inspection to it.
86
87## References
88
89- [Setup](references/setup.md) — installation, Vite config, file structure, app setup, router default options
90- [Type Safety](references/type-safety.md) — register router, `from` param, `strict: false`, type utilities, getRouteApi
91- [Data Loading](references/data-loading.md) — route loaders, Query integration, parallel loading, streaming, deferred data, abort signal, loaderDeps
92- [Search Params](references/search-params.md) — validation, strip/retain middleware, fine-grained subscriptions, debounce, custom serializers
93- [Navigation](references/navigation.md) — Link, active styling, relative navigation, hash, route masks, blocker, scroll restoration
94- [Auth and Context](references/auth-and-context.md) — beforeLoad, context inheritance, pathless layouts, dependency injection, error handling
95- [Code Splitting](references/code-splitting.md) — lazy routes, auto splitting, preloading strategies, programmatic preloading
96- [Virtual File Routes](references/virtual-routes.md) — rootRoute, route, index, layout, physical builders, mixing file-based and code-based routing
97- [Known Issues](references/known-issues.md) — 20 documented issues with fixes, anti-patterns
98- [Loader+Query Patterns](references/loader-query-patterns.md) — ensureQueryData in loaders, parallel loading, critical vs non-critical data, search-param-dependent loaders