- 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
index.md docs/
1# TanStack React Router23TanStack React Router is a modern and scalable routing solution for React applications that provides end-to-end type safety, built-in data fetching, caching, and state management capabilities. It offers a comprehensive type-safe approach to routing with schema-driven search parameter validation, nested layouts with transitions and error boundaries, and advanced features like prefetching and invalidation.45## Package Information67- **Package Name**: @tanstack/react-router8- **Package Type**: npm9- **Language**: TypeScript10- **Installation**: `npm install @tanstack/react-router`1112## Core Imports1314```typescript15import {16Router, createRouter, RouterProvider,17Link, useNavigate, useParams, useSearch,18createRoute, createRootRoute, createFileRoute19} from "@tanstack/react-router";20```2122For CommonJS:2324```javascript25const {26Router, createRouter, RouterProvider,27Link, useNavigate, useParams, useSearch,28createRoute, createRootRoute, createFileRoute29} = require("@tanstack/react-router");30```3132## Basic Usage3334```typescript35import {36createRouter, RouterProvider, createRootRoute,37createRoute, Link, useNavigate, Outlet38} from "@tanstack/react-router";3940// Create root route41const rootRoute = createRootRoute({42component: () => (43<div>44<nav>45<Link to="/">Home</Link>46<Link to="/about">About</Link>47</nav>48<Outlet />49</div>50),51});5253// Create route54const indexRoute = createRoute({55getParentRoute: () => rootRoute,56path: "/",57component: () => <div>Welcome Home!</div>,58});5960const aboutRoute = createRoute({61getParentRoute: () => rootRoute,62path: "/about",63component: () => <div>About Page</div>,64});6566// Create router67const routeTree = rootRoute.addChildren([indexRoute, aboutRoute]);68const router = createRouter({ routeTree });6970// Use in app71function App() {72return <RouterProvider router={router} />;73}74```7576## Architecture7778TanStack React Router is built around several key architectural components:7980- **Router Core**: Central router instance managing navigation state, route matching, and lifecycle81- **Route Definition System**: Declarative route creation with type-safe parameter and search handling82- **Component System**: React components for navigation (Link), rendering (Match, Outlet), and error handling83- **Hook System**: React hooks for accessing router state, navigation, and route data84- **Data Loading**: Integrated loader system with caching, invalidation, and error boundaries85- **SSR Support**: Full server-side rendering capabilities with hydration86- **File-based Routing**: Optional file-based route organization with automatic type generation8788## Capabilities8990### Router Creation & Configuration9192Core router setup and configuration for creating type-safe routing instances with comprehensive options for data loading, caching, and error handling.9394```typescript { .api }95function createRouter<TRouteTree extends AnyRoute>(96options: RouterConstructorOptions<TRouteTree>97): Router<TRouteTree>;9899interface RouterConstructorOptions<TRouteTree extends AnyRoute> {100routeTree: TRouteTree;101history?: RouterHistory;102basepath?: string;103context?: TRouterContext;104defaultPreload?: false | "intent" | "render" | "viewport";105defaultComponent?: RouteComponent;106defaultErrorComponent?: ErrorRouteComponent;107defaultNotFoundComponent?: NotFoundRouteComponent;108}109```110111[Router Creation & Configuration](./router-creation.md)112113### Route Definition & Management114115System for defining routes with type-safe parameters, search handling, data loading, and nested layouts.116117```typescript { .api }118function createRoute<TParentRoute extends AnyRoute = AnyRoute>(119options: RouteOptions<TParentRoute>120): Route<TParentRoute>;121122function createRootRoute<TRouterContext = unknown>(123options?: RootRouteOptions<TRouterContext>124): RootRoute<TRouterContext>;125126function createFileRoute<TFilePath extends string>(127path?: TFilePath128): FileRoute;129```130131[Route Definition & Management](./route-definition.md)132133### React Components134135Essential React components for router setup, navigation, route rendering, and error handling.136137```typescript { .api }138function RouterProvider<TRouter extends AnyRouter, TDehydrated = unknown>(139props: RouterProps<TRouter, TDehydrated>140): JSX.Element;141142function Link<TRouter extends AnyRouter = RegisteredRouter, TFrom extends string = string>(143props: LinkProps<TRouter, TFrom>144): JSX.Element;145146function Match(props: { matchId: string }): JSX.Element;147148function Outlet(): JSX.Element;149```150151[React Components](./react-components.md)152153### React Hooks154155React hooks for accessing router state, navigation functions, route data, and parameters.156157```typescript { .api }158function useRouter<TRouter extends AnyRouter = RegisteredRouter>(): TRouter;159160function useNavigate<TRouter extends AnyRouter = RegisteredRouter>():161UseNavigateResult<TRouter>;162163function useParams<TRouter extends AnyRouter = RegisteredRouter>(164opts?: UseParamsOptions165): ResolveParams<TRouter>;166167function useSearch<TRouter extends AnyRouter = RegisteredRouter>(168opts?: UseSearchOptions169): InferFullSearchSchema<TRouter>;170```171172[React Hooks](./react-hooks.md)173174### Navigation & Links175176Navigation utilities, link components, and programmatic navigation with type-safe parameter handling.177178```typescript { .api }179function redirect<TRouter extends AnyRouter = AnyRouter>(180options: RedirectOptions<TRouter>181): Redirect;182183function createLink<TComp extends React.ComponentType<any>>(184Comp: TComp185): LinkComponent<TComp>;186187function linkOptions<TRouter extends AnyRouter, TFrom extends string>(188options: LinkOptions<TRouter, TFrom>189): LinkOptions<TRouter, TFrom>;190```191192[Navigation & Links](./navigation-links.md)193194### Data Loading & Caching195196Built-in data loading system with loaders, caching, invalidation, and promise handling.197198```typescript { .api }199function defer<T>(promise: Promise<T>): DeferredPromise<T>;200201function useLoaderData<TRouter extends AnyRouter = RegisteredRouter>(202opts?: UseLoaderDataOptions203): ResolveLoaderData<TRouter>;204205function useAwaited<T>(options: AwaitOptions<T>): [T, DeferredPromise<T>];206```207208[Data Loading & Caching](./data-loading.md)209210### Error Handling211212Comprehensive error handling with boundaries, not found handling, and custom error components.213214```typescript { .api }215function CatchBoundary(props: CatchBoundaryProps): JSX.Element;216217function notFound<TRouterContext = unknown>(218options?: NotFoundError219): NotFoundError;220221function isNotFound(obj: any): obj is NotFoundError;222223function isRedirect(obj: any): obj is Redirect;224```225226[Error Handling](./error-handling.md)227228### Server-Side Rendering229230Complete SSR support with server and client components, rendering utilities, and hydration.231232```typescript { .api }233function renderRouterToString<TRouter extends AnyRouter>(234options: RenderRouterToStringOptions<TRouter>235): Promise<string>;236237function renderRouterToStream<TRouter extends AnyRouter>(238options: RenderRouterToStreamOptions<TRouter>239): Promise<ReadableStream>;240```241242[Server-Side Rendering](./ssr.md)243244### Path & Search Utilities245246Low-level utilities for path manipulation, search parameter handling, and URL processing.247248```typescript { .api }249function joinPaths(paths: Array<string | undefined>): string;250251function parseSearchWith<T>(parser: (searchStr: string) => T): (searchStr: string) => T;252253function retainSearchParams<T>(search: T, retain: Array<string | number>): Partial<T>;254255function interpolatePath(path: string, params: Record<string, any>): string;256```257258[Path & Search Utilities](./path-search-utils.md)259260## Types261262### Core Router Types263264```typescript { .api }265interface Router<TRouteTree extends AnyRoute = AnyRoute> {266history: RouterHistory;267state: RouterState;268navigate: (options: NavigateOptions) => Promise<void>;269buildLocation: (options: BuildLocationOptions) => ParsedLocation;270invalidate: () => Promise<void>;271}272273interface RouterState {274location: ParsedLocation;275matches: RouteMatch[];276pendingMatches?: RouteMatch[];277isLoading: boolean;278isTransitioning: boolean;279}280281interface ParsedLocation {282pathname: string;283search: Record<string, any>;284searchStr: string;285hash: string;286href: string;287state: HistoryState;288}289```290291### Route Types292293```typescript { .api }294interface Route<TParentRoute extends AnyRoute = AnyRoute> {295id: string;296path: string;297fullPath: string;298parentRoute?: TParentRoute;299children?: AnyRoute[];300options: RouteOptions;301}302303interface RouteMatch {304id: string;305routeId: string;306pathname: string;307params: Record<string, any>;308search: Record<string, any>;309loaderData?: any;310context: RouteContext;311status: "pending" | "success" | "error" | "idle";312}313```314315### Navigation Types316317```typescript { .api }318interface NavigateOptions<TRouter extends AnyRouter = AnyRouter> {319to?: string;320from?: string;321params?: Record<string, any>;322search?: Record<string, any> | ((prev: any) => Record<string, any>);323hash?: string | ((prev: string) => string);324state?: any;325replace?: boolean;326resetScroll?: boolean;327startTransition?: boolean;328}329330interface LinkOptions<TRouter extends AnyRouter = AnyRouter> extends NavigateOptions<TRouter> {331activeProps?: React.AnchorHTMLAttributes<HTMLAnchorElement>;332inactiveProps?: React.AnchorHTMLAttributes<HTMLAnchorElement>;333preload?: false | "intent" | "render" | "viewport";334preloadDelay?: number;335}336```