- Spec files
npm-tanstack--react-router
Describes: pkg:npm/@tanstack/react-router@1.132.x
- Description
- Modern and scalable routing for React applications with built-in data fetching, caching, and state management capabilities
- Author
- tessl
- Last updated
How to use
npx @tessl/cli registry install tessl/npm-tanstack--react-router@1.132.0
route-definition.md docs/
1# Route Definition & Management23System for defining routes with type-safe parameters, search handling, data loading, and nested layouts. Supports both programmatic route creation and file-based routing patterns.45## Capabilities67### Route Creation89Create route instances with comprehensive configuration options including loaders, components, and validation.1011```typescript { .api }12/**13* Create a route instance with configuration14* @param options - Route configuration options15* @returns Route instance16*/17function createRoute<TParentRoute extends AnyRoute = AnyRoute>(18options: RouteOptions<TParentRoute>19): Route<TParentRoute>;2021interface RouteOptions<TParentRoute extends AnyRoute = AnyRoute> {22/** Function returning parent route */23getParentRoute?: () => TParentRoute;24/** Route path pattern */25path?: string;26/** Route ID for identification */27id?: string;28/** Route component */29component?: RouteComponent;30/** Error boundary component */31errorComponent?: ErrorRouteComponent;32/** Loading/pending component */33pendingComponent?: RouteComponent;34/** Not found component */35notFoundComponent?: NotFoundRouteComponent;36/** Route loader function */37loader?: RouteLoaderFn;38/** Route context function */39beforeLoad?: RouteContextFn;40/** Validation schema for search params */41validateSearch?: SearchValidator;42/** Transform search params */43search?: SearchTransform;44/** Static data */45staticData?: any;46/** Whether route should preload */47shouldReload?: boolean | ((match: RouteMatch) => boolean);48/** Stale time for route data */49staleTime?: number;50/** Garbage collection time */51gcTime?: number;52}53```5455**Usage Examples:**5657```typescript58import { createRoute, createRootRoute } from "@tanstack/react-router";5960// Basic route61const homeRoute = createRoute({62getParentRoute: () => rootRoute,63path: "/",64component: () => <div>Home</div>,65});6667// Route with parameters and loader68const postRoute = createRoute({69getParentRoute: () => rootRoute,70path: "/posts/$postId",71loader: async ({ params }) => {72const post = await fetchPost(params.postId);73return { post };74},75component: ({ useLoaderData }) => {76const { post } = useLoaderData();77return <div>{post.title}</div>;78},79});8081// Route with search validation82const searchRoute = createRoute({83getParentRoute: () => rootRoute,84path: "/search",85validateSearch: (search) => ({86q: search.q || "",87page: Number(search.page) || 1,88}),89component: ({ useSearch }) => {90const { q, page } = useSearch();91return <SearchResults query={q} page={page} />;92},93});94```9596### Root Route Creation9798Create the root route that serves as the top-level route for the application.99100```typescript { .api }101/**102* Create a root route103* @param options - Root route configuration options104* @returns Root route instance105*/106function createRootRoute<TRouterContext = unknown>(107options?: RootRouteOptions<TRouterContext>108): RootRoute<TRouterContext>;109110/**111* Create a root route with typed context112* @returns Function to create root route with context113*/114function createRootRouteWithContext<TRouterContext>(): <TRouter extends AnyRouter = AnyRouter>(115options?: RootRouteOptions<TRouterContext>116) => RootRoute<TRouterContext>;117118interface RootRouteOptions<TRouterContext = unknown> {119/** Root component */120component?: RouteComponent;121/** Root error component */122errorComponent?: ErrorRouteComponent;123/** Root pending component */124pendingComponent?: RouteComponent;125/** Root not found component */126notFoundComponent?: NotFoundRouteComponent;127/** Root loader function */128loader?: (opts: { context: TRouterContext }) => any;129/** Root context function */130beforeLoad?: (opts: { context: TRouterContext }) => any;131}132```133134**Usage Examples:**135136```typescript137import { createRootRoute, createRootRouteWithContext, Outlet } from "@tanstack/react-router";138139// Basic root route140const rootRoute = createRootRoute({141component: () => (142<div>143<nav>Navigation</nav>144<Outlet />145</div>146),147});148149// Root route with typed context150const createRootWithContext = createRootRouteWithContext<{151user: User;152theme: "light" | "dark";153}>();154155const rootRoute = createRootWithContext({156component: () => <App />,157beforeLoad: ({ context }) => {158console.log("User:", context.user);159return { ...context };160},161});162```163164### File-Based Routes165166Create routes based on file system conventions with automatic type generation and file-system-based routing patterns.167168```typescript { .api }169/**170* Create a file-based route with automatic type inference171* @param path - File path for type inference172* @returns Function to create route with file-based typing173*/174function createFileRoute<TFilePath extends keyof FileRoutesByPath>(175path?: TFilePath176): FileRoute<TFilePath>['createRoute'];177178/**179* Create a lazy file route for code splitting180* @param id - File path used as route ID181* @returns Function to create lazy file route182*/183function createLazyFileRoute<TFilePath extends keyof FileRoutesByPath>(184id: TFilePath185): (opts: LazyRouteOptions) => LazyRoute<FileRoutesByPath[TFilePath]['preLoaderRoute']>;186187/**188* File route loader function (deprecated - use loader in createFileRoute options)189* @param path - File path190* @returns Function to define typed loader191*/192function FileRouteLoader<TFilePath extends keyof FileRoutesByPath>(193path: TFilePath194): <TLoaderFn>(loaderFn: TLoaderFn) => TLoaderFn;195```196197### File Route Class198199File route class for programmatic file-based route creation (deprecated in favor of createFileRoute).200201```typescript { .api }202/**203* File route class (deprecated - use createFileRoute instead)204* @deprecated Use createFileRoute('/path/to/file')(options) instead205*/206class FileRoute<207TFilePath extends keyof FileRoutesByPath,208TParentRoute extends AnyRoute = FileRoutesByPath[TFilePath]['parentRoute'],209TId extends RouteConstraints['TId'] = FileRoutesByPath[TFilePath]['id'],210TPath extends RouteConstraints['TPath'] = FileRoutesByPath[TFilePath]['path'],211TFullPath extends RouteConstraints['TFullPath'] = FileRoutesByPath[TFilePath]['fullPath']212> {213/** File path */214path?: TFilePath;215/** Silent mode flag */216silent?: boolean;217218constructor(path?: TFilePath, opts?: { silent: boolean });219220/**221* Create route from file route instance222* @param options - File route options223* @returns Route instance224*/225createRoute<TOptions extends FileBaseRouteOptions>(226options?: TOptions227): Route<TParentRoute, TPath, TFullPath, TFilePath, TId>;228}229```230231**Usage Examples:**232233```typescript234// In routes/index.tsx235export const Route = createFileRoute("/")({236component: Index,237});238239function Index() {240return <div>Home</div>;241}242243// In routes/posts/$postId.tsx244export const Route = createFileRoute("/posts/$postId")({245loader: ({ params }) => fetchPost(params.postId),246component: PostDetail,247});248249// Lazy file route250export const Route = createLazyFileRoute("/posts/$postId")({251component: LazyPostDetail,252});253```254255### Lazy Routes256257Create routes that load components dynamically for code splitting with typed hook access.258259```typescript { .api }260/**261* Create a lazy route for code splitting262* @param id - Route ID263* @returns Function to create lazy route264*/265function createLazyRoute<266TRouter extends AnyRouter = RegisteredRouter,267TId extends string = string,268TRoute extends AnyRoute = RouteById<TRouter['routeTree'], TId>269>(270id: ConstrainLiteral<TId, RouteIds<TRouter['routeTree']>>271): (opts: LazyRouteOptions) => LazyRoute<TRoute>;272273interface LazyRouteOptions {274/** Lazy route component */275component?: LazyRouteComponent;276/** Lazy error component */277errorComponent?: ErrorRouteComponent;278/** Lazy pending component */279pendingComponent?: RouteComponent;280/** Lazy not found component */281notFoundComponent?: NotFoundRouteComponent;282}283```284285### Lazy Route Class286287Lazy route class with typed hooks for accessing route data.288289```typescript { .api }290/**291* Lazy route class with typed hook access292*/293class LazyRoute<TRoute extends AnyRoute> {294/** Lazy route options including ID */295options: { id: string } & LazyRouteOptions;296297constructor(opts: { id: string } & LazyRouteOptions);298299/**300* Access match data for this lazy route301* @param opts - Match selection options302* @returns Route match data303*/304useMatch: UseMatchRoute<TRoute['id']>;305306/**307* Access route context for this lazy route308* @param opts - Context selection options309* @returns Route context310*/311useRouteContext: UseRouteContextRoute<TRoute['id']>;312313/**314* Access search params for this lazy route315* @param opts - Search selection options316* @returns Search parameters317*/318useSearch: UseSearchRoute<TRoute['id']>;319320/**321* Access route params for this lazy route322* @param opts - Params selection options323* @returns Route parameters324*/325useParams: UseParamsRoute<TRoute['id']>;326327/**328* Access loader dependencies for this lazy route329* @param opts - Loader deps selection options330* @returns Loader dependencies331*/332useLoaderDeps: UseLoaderDepsRoute<TRoute['id']>;333334/**335* Access loader data for this lazy route336* @param opts - Loader data selection options337* @returns Loader data338*/339useLoaderData: UseLoaderDataRoute<TRoute['id']>;340341/**342* Access navigation function for this lazy route343* @returns Typed navigation function344*/345useNavigate: () => UseNavigateResult<TRoute['fullPath']>;346}347```348349### Route API350351Access typed API for specific routes with helper methods.352353```typescript { .api }354/**355* Get typed route API for a specific route356* @param id - Route ID357* @returns RouteApi instance358*/359function getRouteApi<TId extends string, TRouter extends AnyRouter = RegisteredRouter>(360id: TId361): RouteApi<TRouter, TId>;362363class RouteApi<TRouter extends AnyRouter, TId extends RouteIds<TRouter>> {364/** Route ID */365id: TId;366367/**368* Use loader data for this route369* @param opts - Options370* @returns Loader data371*/372useLoaderData<TSelected = ResolveLoaderData<TRouter, TId>>(373opts?: {374select?: (data: ResolveLoaderData<TRouter, TId>) => TSelected;375}376): TSelected;377378/**379* Use route context380* @param opts - Options381* @returns Route context382*/383useRouteContext<TSelected = RouteContext<TRouter, TId>>(384opts?: {385select?: (context: RouteContext<TRouter, TId>) => TSelected;386}387): TSelected;388389/**390* Use search params for this route391* @param opts - Options392* @returns Search params393*/394useSearch<TSelected = InferFullSearchSchema<TRouter, TId>>(395opts?: {396select?: (search: InferFullSearchSchema<TRouter, TId>) => TSelected;397}398): TSelected;399400/**401* Use params for this route402* @param opts - Options403* @returns Route params404*/405useParams<TSelected = ResolveParams<TRouter, TId>>(406opts?: {407select?: (params: ResolveParams<TRouter, TId>) => TSelected;408}409): TSelected;410}411```412413### Route Masking414415Create route masks for URL masking and aliasing.416417```typescript { .api }418/**419* Create a route mask for URL masking420* @param options - Masking options421* @returns Route mask configuration422*/423function createRouteMask<TRouteTree extends AnyRoute, TFrom extends string, TTo extends string>(424options: {425routeTree: TRouteTree;426from: TFrom;427to: TTo;428params?: Record<string, any>;429search?: Record<string, any>;430hash?: string;431unmaskOnReload?: boolean;432}433): RouteMask;434```435436## Types437438### Route Types439440```typescript { .api }441interface Route<TParentRoute extends AnyRoute = AnyRoute> {442/** Route ID */443id: string;444/** Route path pattern */445path: string;446/** Full resolved path */447fullPath: string;448/** Parent route */449parentRoute?: TParentRoute;450/** Child routes */451children?: AnyRoute[];452/** Route options */453options: RouteOptions;454/** Add child routes */455addChildren<TChildren extends AnyRoute[]>(children: TChildren): RouteWithChildren<TChildren>;456}457458interface RootRoute<TRouterContext = unknown> extends Route {459/** Root route marker */460isRoot: true;461/** Router context */462context?: TRouterContext;463}464```465466### Route Match Types467468```typescript { .api }469interface RouteMatch {470/** Match ID */471id: string;472/** Route ID this match represents */473routeId: string;474/** Pathname portion */475pathname: string;476/** Route parameters */477params: Record<string, any>;478/** Search parameters */479search: Record<string, any>;480/** Loader data */481loaderData?: any;482/** Route context */483context: RouteContext;484/** Match status */485status: "pending" | "success" | "error" | "idle";486/** Whether match is invalid */487invalid: boolean;488/** Error if any */489error?: unknown;490/** Updated timestamp */491updatedAt: number;492}493```494495### Component Types496497```typescript { .api }498type RouteComponent = React.ComponentType<{499useParams: () => any;500useSearch: () => any;501useLoaderData: () => any;502useRouteContext: () => any;503useNavigate: () => any;504}>;505506type ErrorRouteComponent = React.ComponentType<{507error: Error;508info: { componentStack: string };509reset: () => void;510}>;511512type NotFoundRouteComponent = React.ComponentType<{513data?: any;514}>;515```516517### Loader Types518519```typescript { .api }520type RouteLoaderFn<TRoute extends AnyRoute = AnyRoute> = (521context: LoaderFnContext<TRoute>522) => any | Promise<any>;523524interface LoaderFnContext<TRoute extends AnyRoute = AnyRoute> {525/** Route parameters */526params: ResolveParams<TRoute>;527/** Search parameters */528search: InferFullSearchSchema<TRoute>;529/** Route context */530context: RouteContext<TRoute>;531/** Location object */532location: ParsedLocation;533/** Abort signal */534signal: AbortSignal;535}536```