@tanstack/react-router 1.133.7 → 1.133.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/llms/rules/api.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
declare const _default: "# ActiveLinkOptions type\n\nThe `ActiveLinkOptions` type extends the [`LinkOptions`](../LinkOptionsType.md) type and contains additional options that can be used to describe how a link should be styled when it is active.\n\n```tsx\ntype ActiveLinkOptions = LinkOptions & {\n activeProps?:\n | React.AnchorHTMLAttributes<HTMLAnchorElement>\n | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)\n inactiveProps?:\n | React.AnchorHTMLAttributes<HTMLAnchorElement>\n | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)\n}\n```\n\n## ActiveLinkOptions properties\n\nThe `ActiveLinkOptions` object accepts/contains the following properties:\n\n### `activeProps`\n\n- `React.AnchorHTMLAttributes<HTMLAnchorElement>`\n- Optional\n- The props that will be applied to the anchor element when the link is active\n\n### `inactiveProps`\n\n- Type: `React.AnchorHTMLAttributes<HTMLAnchorElement>`\n- Optional\n- The props that will be applied to the anchor element when the link is inactive\n\n# AsyncRouteComponent type\n\nThe `AsyncRouteComponent` type is used to describe a code-split route component that can be preloaded using a `component.preload()` method.\n\n```tsx\ntype AsyncRouteComponent<TProps> = SyncRouteComponent<TProps> & {\n preload?: () => Promise<void>\n}\n```\n\n# FileRoute class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createFileRoute`](../createFileRouteFunction.md) function instead.\n\nThe `FileRoute` class is a factory that can be used to create a file-based route instance. This route instance can then be used to automatically generate a route tree with the `tsr generate` and `tsr watch` commands.\n\n## `FileRoute` constructor\n\nThe `FileRoute` constructor accepts a single argument: the `path` of the file that the route will be generated for.\n\n### Constructor options\n\n- Type: `string` literal\n- Required, but **automatically inserted and updated by the `tsr generate` and `tsr watch` commands**.\n- The full path of the file that the route will be generated from.\n\n### Constructor returns\n\n- An instance of the `FileRoute` class that can be used to create a route.\n\n## `FileRoute` methods\n\nThe `FileRoute` class implements the following method(s):\n\n### `.createRoute` method\n\nThe `createRoute` method is a method that can be used to configure the file route instance. It accepts a single argument: the `options` that will be used to configure the file route instance.\n\n#### .createRoute options\n\n- Type: `Omit<RouteOptions, 'getParentRoute' | 'path' | 'id'>`\n- [`RouteOptions`](../RouteOptionsType.md)\n- Optional\n- The same options that are available to the `Route` class, but with the `getParentRoute`, `path`, and `id` options omitted since they are unnecessary for file-based routing.\n\n#### .createRoute returns\n\nA [`Route`](../RouteType.md) instance that can be used to configure the route to be inserted into the route-tree.\n\n> \u26A0\uFE0F Note: For `tsr generate` and `tsr watch` to work properly, the file route instance must be exported from the file using the `Route` identifier.\n\n### Examples\n\n```tsx\nimport { FileRoute } from '@tanstack/react-router'\n\nexport const Route = new FileRoute('/').createRoute({\n loader: () => {\n return 'Hello World'\n },\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# LinkOptions type\n\nThe `LinkOptions` type extends the [`NavigateOptions`](../NavigateOptionsType.md) type and contains additional options that can be used by TanStack Router when handling actual anchor element attributes.\n\n```tsx\ntype LinkOptions = NavigateOptions & {\n target?: HTMLAnchorElement['target']\n activeOptions?: ActiveOptions\n preload?: false | 'intent'\n preloadDelay?: number\n disabled?: boolean\n}\n```\n\n## LinkOptions properties\n\nThe `LinkOptions` object accepts/contains the following properties:\n\n### `target`\n\n- Type: `HTMLAnchorElement['target']`\n- Optional\n- The standard anchor tag target attribute\n\n### `activeOptions`\n\n- Type: `ActiveOptions`\n- Optional\n- The options that will be used to determine if the link is active\n\n### `preload`\n\n- Type: `false | 'intent' | 'viewport' | 'render'`\n- Optional\n- If set, the link's preloading strategy will be set to this value.\n- See the [Preloading guide](../../../guide/preloading.md) for more information.\n\n### `preloadDelay`\n\n- Type: `number`\n- Optional\n- Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled.\n\n### `disabled`\n\n- Type: `boolean`\n- Optional\n- If true, will render the link without the href attribute\n\n# LinkProps type\n\nThe `LinkProps` type extends the [`ActiveLinkOptions`](../ActiveLinkOptionsType.md) and `React.AnchorHTMLAttributes<HTMLAnchorElement>` types and contains additional props specific to the `Link` component.\n\n```tsx\ntype LinkProps = ActiveLinkOptions &\n Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'children'> & {\n children?:\n | React.ReactNode\n | ((state: { isActive: boolean }) => React.ReactNode)\n }\n```\n\n## LinkProps properties\n\n- All of the props from [`ActiveLinkOptions`](../ActiveLinkOptionsType.md)\n- All of the props from `React.AnchorHTMLAttributes<HTMLAnchorElement>`\n\n#### `children`\n\n- Type: `React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode)`\n- Optional\n- The children that will be rendered inside of the anchor element. If a function is provided, it will be called with an object that contains the `isActive` boolean value that can be used to determine if the link is active.\n\n# MatchRouteOptions type\n\nThe `MatchRouteOptions` type is used to describe the options that can be used when matching a route.\n\n```tsx\ninterface MatchRouteOptions {\n pending?: boolean\n caseSensitive?: boolean\n includeSearch?: boolean\n fuzzy?: boolean\n}\n```\n\n## MatchRouteOptions properties\n\nThe `MatchRouteOptions` type has the following properties:\n\n### `pending` property\n\n- Type: `boolean`\n- Optional\n- If `true`, will match against pending location instead of the current location\n\n### `caseSensitive` property\n\n- Type: `boolean`\n- Optional\n- If `true`, will match against the current location with case sensitivity\n\n### `includeSearch` property\n\n- Type: `boolean`\n- Optional\n- If `true`, will match against the current location's search params using a deep inclusive check. e.g. `{ a: 1 }` will match for a current location of `{ a: 1, b: 2 }`\n\n### `fuzzy` property\n\n- Type: `boolean`\n- Optional\n- If `true`, will match against the current location using a fuzzy match. e.g. `/posts` will match for a current location of `/posts/123`\n\n# NavigateOptions type\n\nThe `NavigateOptions` type is used to describe the options that can be used when describing a navigation action in TanStack Router.\n\n```tsx\ntype NavigateOptions = ToOptions & {\n replace?: boolean\n resetScroll?: boolean\n hashScrollIntoView?: boolean | ScrollIntoViewOptions\n viewTransition?: boolean | ViewTransitionOptions\n ignoreBlocker?: boolean\n reloadDocument?: boolean\n href?: string\n}\n```\n\n## NavigateOptions properties\n\nThe `NavigateOptions` object accepts the following properties:\n\n### `replace`\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`.\n- If `true`, the location will be committed to the browser history using `history.replace` instead of `history.push`.\n\n### `resetScroll`\n\n- Type: `boolean`\n- Optional\n- Defaults to `true` so that the scroll position will be reset to 0,0 after the location is committed to the browser history.\n- If `false`, the scroll position will not be reset to 0,0 after the location is committed to history.\n\n### `hashScrollIntoView`\n\n- Type: `boolean | ScrollIntoViewOptions`\n- Optional\n- Defaults to `true` so the element with an id matching the hash will be scrolled into view after the location is committed to history.\n- If `false`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.\n- If an object is provided, it will be passed to the `scrollIntoView` method as options.\n- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on `ScrollIntoViewOptions`.\n\n### `viewTransition`\n\n- Type: `boolean | ViewTransitionOptions`\n- Optional\n- Defaults to `false`.\n- If `true`, navigation will be called using `document.startViewTransition()`.\n- If [`ViewTransitionOptions`](../ViewTransitionOptionsType.md), route navigations will be called using `document.startViewTransition({update, types})` where `types` will be the strings array passed with `ViewTransitionOptions[\"types\"]`. If the browser does not support viewTransition types, the navigation will fall back to normal `document.startTransition()`, same as if `true` was passed.\n- If the browser does not support this api, this option will be ignored.\n- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.\n- See [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types) for more information on viewTransition types\n\n### `ignoreBlocker`\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`.\n- If `true`, navigation will ignore any blockers that might prevent it.\n\n### `reloadDocument`\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`.\n- If `true`, navigation to a route inside of router will trigger a full page load instead of the traditional SPA navigation.\n\n### `href`\n\n- Type: `string`\n- Optional\n- This can be used instead of `to` to navigate to a fully built href, e.g. pointing to an external target.\n\n- [`ToOptions`](../ToOptionsType.md)\n\n# NotFoundError\n\nThe `NotFoundError` type is used to represent a not-found error in TanStack Router.\n\n```tsx\nexport type NotFoundError = {\n global?: boolean\n data?: any\n throw?: boolean\n routeId?: string\n headers?: HeadersInit\n}\n```\n\n## NotFoundError properties\n\nThe `NotFoundError` object accepts/contains the following properties:\n\n### `global` property (\u26A0\uFE0F deprecated, use `routeId: rootRouteId` instead)\n\n- Type: `boolean`\n- Optional - `default: false`\n- If true, the not-found error will be handled by the `notFoundComponent` of the root route instead of bubbling up from the route that threw it. This has the same behavior as importing the root route and calling `RootRoute.notFound()`.\n\n### `data` property\n\n- Type: `any`\n- Optional\n- Custom data that is passed into to `notFoundComponent` when the not-found error is handled\n\n### `throw` property\n\n- Type: `boolean`\n- Optional - `default: false`\n- If provided, will throw the not-found object instead of returning it. This can be useful in places where `throwing` in a function might cause it to have a return type of `never`. In that case, you can use `notFound({ throw: true })` to throw the not-found object instead of returning it.\n\n### `route` property\n\n- Type: `string`\n- Optional\n- The ID of the route that will attempt to handle the not-found error. If the route does not have a `notFoundComponent`, the error will bubble up to the parent route (and be handled by the root route if necessary). By default, TanStack Router will attempt to handle the not-found error with the route that threw it.\n\n### `headers` property\n\n- Type: `HeadersInit`\n- Optional\n- HTTP headers to be included when the not-found error is handled on the server side.\n\n# NotFoundRoute class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the `notFoundComponent` route option that is present during route configuration.\n> See the [Not Found Errors guide](../../../guide/not-found-errors.md) for more information.\n\nThe `NotFoundRoute` class extends the `Route` class and can be used to create a not found route instance. A not found route instance can be passed to the `routerOptions.notFoundRoute` option to configure a default not-found/404 route for every branch of the route tree.\n\n## Constructor options\n\nThe `NotFoundRoute` constructor accepts an object as its only argument.\n\n- Type:\n\n```tsx\nOmit<\n RouteOptions,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n>\n```\n\n- [RouteOptions](../RouteOptionsType.md)\n- Required\n- The options that will be used to configure the not found route instance.\n\n## Examples\n\n```tsx\nimport { NotFoundRoute, createRouter } from '@tanstack/react-router'\nimport { Route as rootRoute } from './routes/__root'\nimport { routeTree } from './routeTree.gen'\n\nconst notFoundRoute = new NotFoundRoute({\n getParentRoute: () => rootRoute,\n component: () => <div>Not found!!!</div>,\n})\n\nconst router = createRouter({\n routeTree,\n notFoundRoute,\n})\n\n// ... other code\n```\n\n# ParsedHistoryState type\n\nThe `ParsedHistoryState` type represents a parsed state object. Additionally to `HistoryState`, it contains the index and the unique key of the route.\n\n```tsx\nexport type ParsedHistoryState = HistoryState & {\n key?: string // TODO: Remove in v2 - use __TSR_key instead\n __TSR_key?: string\n __TSR_index: number\n}\n```\n\n# ParsedLocation type\n\nThe `ParsedLocation` type represents a parsed location in TanStack Router. It contains a lot of useful information about the current location, including the pathname, search params, hash, location state, and route masking information.\n\n```tsx\ninterface ParsedLocation {\n href: string\n pathname: string\n search: TFullSearchSchema\n searchStr: string\n state: ParsedHistoryState\n hash: string\n maskedLocation?: ParsedLocation\n unmaskOnReload?: boolean\n}\n```\n\n# Redirect type\n\nThe `Redirect` type is used to represent a redirect action in TanStack Router.\n\n```tsx\nexport type Redirect = {\n statusCode?: number\n throw?: any\n headers?: HeadersInit\n} & NavigateOptions\n```\n\n- [`NavigateOptions`](../NavigateOptionsType.md)\n\n## Redirect properties\n\nThe `Redirect` object accepts/contains the following properties:\n\n### `statusCode` property\n\n- Type: `number`\n- Optional\n- The HTTP status code to use when redirecting\n\n### `throw` property\n\n- Type: `any`\n- Optional\n- If provided, will throw the redirect object instead of returning it. This can be useful in places where `throwing` in a function might cause it to have a return type of `never`. In that case, you can use `redirect({ throw: true })` to throw the redirect object instead of returning it.\n\n### `headers` property\n\n- Type: `HeadersInit`\n- Optional\n- The HTTP headers to use when redirecting.\n\n### Navigation Properties\n\nSince `Redirect` extends `NavigateOptions`, it also supports navigation properties:\n\n- **`to`**: Use for internal application routes (e.g., `/dashboard`, `../profile`)\n- **`href`**: Use for external URLs (e.g., `https://example.com`, `https://authprovider.com`)\n\n> **Important**: For external URLs, always use the `href` property instead of `to`. The `to` property is designed for internal navigation within your application.\n\n# Register type\n\nThis type is used to register a route tree with a router instance. Doing so unlocks the full type safety of TanStack Router, including top-level exports from the `@tanstack/react-router` package.\n\n```tsx\nexport type Register = {\n // router: [Your router type here]\n}\n```\n\nTo register a route tree with a router instance, use declaration merging to add the type of your router instance to the Register interface under the `router` property:\n\n## Examples\n\n```tsx\nconst router = createRouter({\n // ...\n})\n\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n```\n\n# RootRoute class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createRootRoute`](../createRootRouteFunction.md) function instead.\n\nThe `RootRoute` class extends the `Route` class and can be used to create a root route instance. A root route instance can then be used to create a route tree.\n\n## `RootRoute` constructor\n\nThe `RootRoute` constructor accepts an object as its only argument.\n\n### Constructor options\n\nThe options that will be used to configure the root route instance.\n\n- Type:\n\n```tsx\nOmit<\n RouteOptions,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n>\n```\n\n- [`RouteOptions`](../RouteOptionsType.md)\n- Optional\n\n## Constructor returns\n\nA new [`Route`](../RouteType.md) instance.\n\n## Examples\n\n```tsx\nimport { RootRoute, createRouter, Outlet } from '@tanstack/react-router'\n\nconst rootRoute = new RootRoute({\n component: () => <Outlet />,\n // ... root route options\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst router = createRouter({\n routeTree,\n})\n```\n\n# RouteApi class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`getRouteApi`](../getRouteApiFunction.md) function instead.\n\nThe `RouteApi` class provides type-safe version of common hooks like `useParams`, `useSearch`, `useRouteContext`, `useNavigate`, `useLoaderData`, and `useLoaderDeps` that are pre-bound to a specific route ID and corresponding registered route types.\n\n## Constructor options\n\nThe `RouteApi` constructor accepts a single argument: the `options` that will be used to configure the `RouteApi` instance.\n\n### `opts.routeId` option\n\n- Type: `string`\n- Required\n- The route ID to which the `RouteApi` instance will be bound\n\n## Constructor returns\n\n- An instance of the [`RouteApi`](../RouteApiType.md) that is pre-bound to the route ID that it was called with.\n\n## Examples\n\n```tsx\nimport { RouteApi } from '@tanstack/react-router'\n\nconst routeApi = new RouteApi({ id: '/posts' })\n\nexport function PostsPage() {\n const posts = routeApi.useLoaderData()\n // ...\n}\n```\n\n# RouteApi Type\n\nThe `RouteApi` describes an instance that provides type-safe versions of common hooks like `useParams`, `useSearch`, `useRouteContext`, `useNavigate`, `useLoaderData`, and `useLoaderDeps` that are pre-bound to a specific route ID and corresponding registered route types.\n\n## `RouteApi` properties and methods\n\nThe `RouteApi` has the following properties and methods:\n\n### `useMatch` method\n\n```tsx\n useMatch<TSelected = TAllContext>(opts?: {\n select?: (match: TAllContext) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useMatch`](../useMatchHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: RouteMatch) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useMatch`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `RouteMatch` object or a loosened version of the `RouteMatch` object if `opts.strict` is `false`.\n\n### `useRouteContext` method\n\n```tsx\n useRouteContext<TSelected = TAllContext>(opts?: {\n select?: (search: TAllContext) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useRouteContext`](../useRouteContextHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: RouteContext) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useRouteContext`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `RouteContext` object or a loosened version of the `RouteContext` object if `opts.strict` is `false`.\n\n### `useSearch` method\n\n```tsx\n useSearch<TSelected = TFullSearchSchema>(opts?: {\n select?: (search: TFullSearchSchema) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useSearch`](../useSearchHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: TFullSearchSchema) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useSearch`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `TFullSearchSchema` object or a loosened version of the `TFullSearchSchema` object if `opts.strict` is `false`.\n\n### `useParams` method\n\n```tsx\n useParams<TSelected = TAllParams>(opts?: {\n select?: (params: TAllParams) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useParams`](../useParamsHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: TAllParams) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useParams`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `TAllParams` object or a loosened version of the `TAllParams` object if `opts.strict` is `false`.\n\n### `useLoaderData` method\n\n```tsx\n useLoaderData<TSelected = TLoaderData>(opts?: {\n select?: (search: TLoaderData) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useLoaderData`](../useLoaderDataHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: TLoaderData) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useLoaderData`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `TLoaderData` object or a loosened version of the `TLoaderData` object if `opts.strict` is `false`.\n\n### `useLoaderDeps` method\n\n```tsx\n useLoaderDeps<TSelected = TLoaderDeps>(opts?: {\n select?: (search: TLoaderDeps) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useLoaderDeps`](../useLoaderDepsHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: TLoaderDeps) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useLoaderDeps`.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `TLoaderDeps` object.\n\n### `useNavigate` method\n\n```tsx\n useNavigate(): // navigate function\n```\n\n- A type-safe version of [`useNavigate`](../useNavigateHook.md) that is pre-bound to the route ID that the `RouteApi` instance was created with.\n\n# Route class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createRoute`](../createRouteFunction.md) function instead.\n\nThe `Route` class implements the `RouteApi` class and can be used to create route instances. A route instance can then be used to create a route tree.\n\n## `Route` constructor\n\nThe `Route` constructor accepts an object as its only argument.\n\n### Constructor options\n\n- Type: [`RouteOptions`](../RouteOptionsType.md)\n- Required\n- The options that will be used to configure the route instance\n\n### Constructor returns\n\nA new [`Route`](../RouteType.md) instance.\n\n## Examples\n\n```tsx\nimport { Route } from '@tanstack/react-router'\nimport { rootRoute } from './__root'\n\nconst indexRoute = new Route({\n getParentRoute: () => rootRoute,\n path: '/',\n loader: () => {\n return 'Hello World'\n },\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = indexRoute.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# RouteMask type\n\nThe `RouteMask` type extends the [`ToOptions`](../ToOptionsType.md) type and has other the necessary properties to create a route mask.\n\n## RouteMask properties\n\nThe `RouteMask` type accepts an object with the following properties:\n\n### `...ToOptions`\n\n- Type: [`ToOptions`](../ToOptionsType.md)\n- Required\n- The options that will be used to configure the route mask\n\n### `options.routeTree`\n\n- Type: `TRouteTree`\n- Required\n- The route tree that this route mask will support\n\n### `options.unmaskOnReload`\n\n- Type: `boolean`\n- Optional\n- If `true`, the route mask will be removed when the page is reloaded\n\n# RouteMatch type\n\nThe `RouteMatch` type represents a route match in TanStack Router.\n\n```tsx\ninterface RouteMatch {\n id: string\n routeId: string\n pathname: string\n params: Route['allParams']\n status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound'\n isFetching: false | 'beforeLoad' | 'loader'\n showPending: boolean\n error: unknown\n paramsError: unknown\n searchError: unknown\n updatedAt: number\n loaderData?: Route['loaderData']\n context: Route['allContext']\n search: Route['fullSearchSchema']\n fetchedAt: number\n abortController: AbortController\n cause: 'enter' | 'stay'\n ssr?: boolean | 'data-only'\n}\n```\n\n# RouteOptions type\n\nThe `RouteOptions` type is used to describe the options that can be used when creating a route.\n\n## RouteOptions properties\n\nThe `RouteOptions` type accepts an object with the following properties:\n\n### `getParentRoute` method\n\n- Type: `() => TParentRoute`\n- Required\n- A function that returns the parent route of the route being created. This is required to provide full type safety to child route configurations and to ensure that the route tree is built correctly.\n\n### `path` property\n\n- Type: `string`\n- Required, unless an `id` is provided to configure the route as a pathless layout route\n- The path segment that will be used to match the route.\n\n### `id` property\n\n- Type: `string`\n- Optional, but required if a `path` is not provided\n- The unique identifier for the route if it is to be configured as a pathless layout route. If provided, the route will not match against the location pathname and its routes will be flattened into its parent route for matching.\n\n### `component` property\n\n- Type: `RouteComponent` or `LazyRouteComponent`\n- Optional - Defaults to `<Outlet />`\n- The content to be rendered when the route is matched.\n\n### `errorComponent` property\n\n- Type: `RouteComponent` or `LazyRouteComponent`\n- Optional - Defaults to `routerOptions.defaultErrorComponent`\n- The content to be rendered when the route encounters an error.\n\n### `pendingComponent` property\n\n- Type: `RouteComponent` or `LazyRouteComponent`\n- Optional - Defaults to `routerOptions.defaultPendingComponent`\n- The content to be rendered if and when the route is pending and has reached its pendingMs threshold.\n\n### `notFoundComponent` property\n\n- Type: `NotFoundRouteComponent` or `LazyRouteComponent`\n- Optional - Defaults to `routerOptions.defaultNotFoundComponent`\n- The content to be rendered when the route is not found.\n\n### `validateSearch` method\n\n- Type: `(rawSearchParams: unknown) => TSearchSchema`\n- Optional\n- A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router.\n- Optionally, the parameter type can be tagged with the `SearchSchemaInput` type like this: `(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema`. If this tag is present, `TSearchSchemaInput` will be used to type the `search` property of `<Link />` and `navigate()` **instead of** `TSearchSchema`. The difference between `TSearchSchemaInput` and `TSearchSchema` can be useful, for example, to express optional search parameters.\n\n### `search.middlewares` property\n\n- Type: `(({search: TSearchSchema, next: (newSearch: TSearchSchema) => TSearchSchema}) => TSearchSchema)[]`\n- Optional\n- Search middlewares are functions that transform the search parameters when generating new links for a route or its descendants.\n- A search middleware is passed in the current search (if it is the first middleware to run) or is invoked by the previous middleware calling `next`.\n\n### `parseParams` method (\u26A0\uFE0F deprecated, use `params.parse` instead)\n\n- Type: `(rawParams: Record<string, string>) => TParams`\n- Optional\n- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.\n\n### `stringifyParams` method (\u26A0\uFE0F deprecated, use `params.stringify` instead)\n\n- Type: `(params: TParams) => Record<string, string>`\n- Required if `parseParams` is provided\n- A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of `Record<string, string>` mapping.\n\n### `params.parse` method\n\n- Type: `(rawParams: Record<string, string>) => TParams`\n- Optional\n- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.\n\n### `params.stringify` method\n\n- Type: `(params: TParams) => Record<string, string>`\n- A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of `Record<string, string>` mapping.\n\n### `beforeLoad` method\n\n- Type:\n\n```tsx\ntype beforeLoad = (\n opts: RouteMatch & {\n search: TFullSearchSchema\n abortController: AbortController\n preload: boolean\n params: TAllParams\n context: TParentContext\n location: ParsedLocation\n navigate: NavigateFn<AnyRoute> // @deprecated\n buildLocation: BuildLocationFn<AnyRoute>\n cause: 'enter' | 'stay'\n },\n) => Promise<TRouteContext> | TRouteContext | void\n```\n\n- Optional\n- [`ParsedLocation`](../ParsedLocationType.md)\n- This async function is called before a route is loaded. If an error is thrown here, the route's loader will not be called and the route will not render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail.\n- If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.\n- If this function returns a `TRouteContext` object, that object will be merged into the route's context and be made available in the `loader` and other related route components/methods.\n- It's common to use this function to check if a user is authenticated and redirect them to a login page if they are not. To do this, you can either return or throw a `redirect` object from this function.\n\n> \uD83D\uDEA7 `opts.navigate` has been deprecated and will be removed in the next major release. Use `throw redirect({ to: '/somewhere' })` instead. Read more about the `redirect` function [here](../redirectFunction.md).\n\n### `loader` method\n\n- Type:\n\n```tsx\ntype loader = (\n opts: RouteMatch & {\n abortController: AbortController\n cause: 'preload' | 'enter' | 'stay'\n context: TAllContext\n deps: TLoaderDeps\n location: ParsedLocation\n params: TAllParams\n preload: boolean\n parentMatchPromise: Promise<MakeRouteMatchFromRoute<TParentRoute>>\n navigate: NavigateFn<AnyRoute> // @deprecated\n route: AnyRoute\n },\n) => Promise<TLoaderData> | TLoaderData | void\n```\n\n- Optional\n- [`ParsedLocation`](../ParsedLocationType.md)\n- This async function is called when a route is matched and passed the route's match object. If an error is thrown here, the route will be put into an error state and the error will be thrown during render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail.\n- If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.\n- If this function returns a `TLoaderData` object, that object will be stored on the route match until the route match is no longer active. It can be accessed using the `useLoaderData` hook in any component that is a child of the route match before another `<Outlet />` is rendered.\n- Deps must be returned by your `loaderDeps` function in order to appear.\n\n> \uD83D\uDEA7 `opts.navigate` has been deprecated and will be removed in the next major release. Use `throw redirect({ to: '/somewhere' })` instead. Read more about the `redirect` function [here](../redirectFunction.md).\n\n### `loaderDeps` method\n\n- Type:\n\n```tsx\ntype loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>\n```\n\n- Optional\n- A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation.\n- By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here.\n- If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the `loader`'s `deps` argument.\n\n### `staleTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultStaleTime`, which defaults to `0`\n- The amount of time in milliseconds that a route match's loader data will be considered fresh. If a route match is matched again within this time frame, its loader data will not be reloaded.\n\n### `preloadStaleTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultPreloadStaleTime`, which defaults to `30_000` ms (30 seconds)\n- The amount of time in milliseconds that a route match's loader data will be considered fresh when preloading. If a route match is preloaded again within this time frame, its loader data will not be reloaded. If a route match is loaded (for navigation) within this time frame, the normal `staleTime` is used instead.\n\n### `gcTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes.\n- The amount of time in milliseconds that a route match's loader data will be kept in memory after a preload or it is no longer in use.\n\n### `shouldReload` property\n\n- Type: `boolean | ((args: LoaderArgs) => boolean)`\n- Optional\n- If `false` or returns `false`, the route match's loader data will not be reloaded on subsequent matches.\n- If `true` or returns `true`, the route match's loader data will be reloaded on subsequent matches.\n- If `undefined` or returns `undefined`, the route match's loader data will adhere to the default stale-while-revalidate behavior.\n\n### `caseSensitive` property\n\n- Type: `boolean`\n- Optional\n- If `true`, this route will be matched as case-sensitive.\n\n### `wrapInSuspense` property\n\n- Type: `boolean`\n- Optional\n- If `true`, this route will be forcefully wrapped in a suspense boundary, regardless if a reason is found to do so from inspecting its provided components.\n\n### `pendingMs` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultPendingMs`, which defaults to `1000`\n- The threshold in milliseconds that a route must be pending before its `pendingComponent` is shown.\n\n### `pendingMinMs` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultPendingMinMs` which defaults to `500`\n- The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second.\n\n### `preloadMaxAge` property\n\n- Type: `number`\n- Optional\n- Defaults to `30_000` ms (30 seconds)\n- The maximum amount of time in milliseconds that a route's preloaded route data will be cached for. If a route is not matched within this time frame, its loader data will be discarded.\n\n### `preSearchFilters` property (\u26A0\uFE0F deprecated, use `search.middlewares` instead)\n\n- Type: `((search: TFullSearchSchema) => TFullSearchSchema)[]`\n- Optional\n- An array of functions that will be called when generating any new links to this route or its grandchildren.\n- Each function will be called with the current search params and should return a new search params object that will be used to generate the link.\n- It has a `pre` prefix because it is called before the user-provided function that is passed to `navigate`/`Link` etc has a chance to modify the search params.\n\n### `postSearchFilters` property (\u26A0\uFE0F deprecated, use `search.middlewares` instead)\n\n- Type: `((search: TFullSearchSchema) => TFullSearchSchema)[]`\n- Optional\n- An array of functions that will be called when generating any new links to this route or its grandchildren.\n- Each function will be called with the current search params and should return a new search params object that will be used to generate the link.\n- It has a `post` prefix because it is called after the user-provided function that is passed to `navigate`/`Link` etc has modified the search params.\n\n### `onError` property\n\n- Type: `(error: any) => void`\n- Optional\n- A function that will be called when an error is thrown during a navigation or preload event.\n- If this function throws a [`redirect`](../redirectFunction.md), then the router will process and apply the redirect immediately.\n\n### `onEnter` property\n\n- Type: `(match: RouteMatch) => void`\n- Optional\n- A function that will be called when a route is matched and loaded after not being matched in the previous location.\n\n### `onStay` property\n\n- Type: `(match: RouteMatch) => void`\n- Optional\n- A function that will be called when a route is matched and loaded after being matched in the previous location.\n\n### `onLeave` property\n\n- Type: `(match: RouteMatch) => void`\n- Optional\n- A function that will be called when a route is no longer matched after being matched in the previous location.\n\n### `onCatch` property\n\n- Type: `(error: Error, errorInfo: ErrorInfo) => void`\n- Optional - Defaults to `routerOptions.defaultOnCatch`\n- A function that will be called when errors are caught when the route encounters an error.\n\n### `remountDeps` method\n\n- Type:\n\n```tsx\ntype remountDeps = (opts: RemountDepsOptions) => any\n\ninterface RemountDepsOptions<\n in out TRouteId,\n in out TFullSearchSchema,\n in out TAllParams,\n in out TLoaderDeps,\n> {\n routeId: TRouteId\n search: TFullSearchSchema\n params: TAllParams\n loaderDeps: TLoaderDeps\n}\n```\n\n- Optional\n- A function that will be called to determine whether a route component shall be remounted after navigation. If this function returns a different value than previously, it will remount.\n- The return value needs to be JSON serializable.\n- By default, a route component will not be remounted if it stays active after a navigation.\n\nExample:\nIf you want to configure to remount a route component upon `params` change, use:\n\n```tsx\nremountDeps: ({ params }) => params\n```\n\n### `headers` method\n\n- Type:\n\n```tsx\ntype headers = (opts: {\n matches: Array<RouteMatch>\n match: RouteMatch\n params: TAllParams\n loaderData?: TLoaderData\n}) => Promise<Record<string, string>> | Record<string, string>\n```\n\n- Optional\n- Allows you to specify custom HTTP headers to be sent when this route is rendered during SSR. The function receives the current match context and should return a plain object of header name/value pairs.\n\n### `head` method\n\n- Type:\n\n```tsx\ntype head = (ctx: {\n matches: Array<RouteMatch>\n match: RouteMatch\n params: TAllParams\n loaderData?: TLoaderData\n}) =>\n | Promise<{\n links?: RouteMatch['links']\n scripts?: RouteMatch['headScripts']\n meta?: RouteMatch['meta']\n styles?: RouteMatch['styles']\n }>\n | {\n links?: RouteMatch['links']\n scripts?: RouteMatch['headScripts']\n meta?: RouteMatch['meta']\n styles?: RouteMatch['styles']\n }\n```\n\n- Optional\n- Returns additional elements to inject into the document `<head>` for this route. Use it to add route-level SEO metadata, preload links, inline styles, or custom scripts.\n\n### `scripts` method\n\n- Type:\n\n```tsx\ntype scripts = (ctx: {\n matches: Array<RouteMatch>\n match: RouteMatch\n params: TAllParams\n loaderData?: TLoaderData\n}) => Promise<RouteMatch['scripts']> | RouteMatch['scripts']\n```\n\n- Optional\n- A shorthand helper to return only `<script>` elements. Equivalent to returning the `scripts` field from the `head` method.\n\n### `codeSplitGroupings` property\n\n- Type: `Array<Array<'loader' | 'component' | 'pendingComponent' | 'notFoundComponent' | 'errorComponent'>>`\n- Optional\n- Fine-grained control over how the router groups lazy-loaded pieces of a route into chunks. Each inner array represents a group of assets that will be placed into the same bundle during code-splitting.\n\n# Route type\n\nThe `Route` type is used to describe a route instance.\n\n## `Route` properties and methods\n\nAn instance of the `Route` has the following properties and methods:\n\n### `.addChildren` method\n\n- Type: `(children: Route[]) => this`\n- Adds child routes to the route instance and returns the route instance (but with updated types to reflect the new children).\n\n### `.update` method\n\n- Type: `(options: Partial<UpdatableRouteOptions>) => this`\n- Updates the route instance with new options and returns the route instance (but with updated types to reflect the new options).\n- In some circumstances, it can be useful to update a route instance's options after it has been created to avoid circular type references.\n- ...`RouteApi` methods\n\n### `.lazy` method\n\n- Type: `(lazyImporter: () => Promise<Partial<UpdatableRouteOptions>>) => this`\n- Updates the route instance with a new lazy importer which will be resolved lazily when loading the route. This can be useful for code splitting.\n\n### ...`RouteApi` methods\n\n- All of the methods from [`RouteApi`](../RouteApiType.md) are available.\n\n# Router Class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createRouter`](../createRouterFunction.md) function instead.\n\nThe `Router` class is used to instantiate a new router instance.\n\n## `Router` constructor\n\nThe `Router` constructor accepts a single argument: the `options` that will be used to configure the router instance.\n\n### Constructor options\n\n- Type: [`RouterOptions`](../RouterOptionsType.md)\n- Required\n- The options that will be used to configure the router instance.\n\n### Constructor returns\n\n- An instance of the [`Router`](../RouterType.md).\n\n## Examples\n\n```tsx\nimport { Router, RouterProvider } from '@tanstack/react-router'\nimport { routeTree } from './routeTree.gen'\n\nconst router = new Router({\n routeTree,\n defaultPreload: 'intent',\n})\n\nexport default function App() {\n return <RouterProvider router={router} />\n}\n```\n\n# RouterEvents type\n\nThe `RouterEvents` type contains all of the events that the router can emit. Each top-level key of this type, represents the name of an event that the router can emit. The values of the keys are the event payloads.\n\n```tsx\ntype RouterEvents = {\n onBeforeNavigate: {\n type: 'onBeforeNavigate'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onBeforeLoad: {\n type: 'onBeforeLoad'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onLoad: {\n type: 'onLoad'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onResolved: {\n type: 'onResolved'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onBeforeRouteMount: {\n type: 'onBeforeRouteMount'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onInjectedHtml: {\n type: 'onInjectedHtml'\n promise: Promise<string>\n }\n onRendered: {\n type: 'onRendered'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n }\n}\n```\n\n## RouterEvents properties\n\nOnce an event is emitted, the following properties will be present on the event payload.\n\n### `type` property\n\n- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved`\n- The type of the event\n- This is useful for discriminating between events in a listener function.\n\n### `fromLocation` property\n\n- Type: [`ParsedLocation`](../ParsedLocationType.md)\n- The location that the router is transitioning from.\n\n### `toLocation` property\n\n- Type: [`ParsedLocation`](../ParsedLocationType.md)\n- The location that the router is transitioning to.\n\n### `pathChanged` property\n\n- Type: `boolean`\n- `true` if the path has changed between the `fromLocation` and `toLocation`.\n\n### `hrefChanged` property\n\n- Type: `boolean`\n- `true` if the href has changed between the `fromLocation` and `toLocation`.\n\n## Example\n\n```tsx\nimport { createRouter } from '@tanstack/react-router'\nimport { routeTree } from './routeTree.gen'\n\nconst router = createRouter({ routeTree })\n\nconst unsub = router.subscribe('onResolved', (evt) => {\n // ...\n})\n```\n\n# RouterOptions\n\nThe `RouterOptions` type contains all of the options that can be used to configure a router instance.\n\n## RouterOptions properties\n\nThe `RouterOptions` type accepts an object with the following properties and methods:\n\n### `routeTree` property\n\n- Type: `AnyRoute`\n- Required\n- The route tree that will be used to configure the router instance.\n\n### `history` property\n\n- Type: `RouterHistory`\n- Optional\n- The history object that will be used to manage the browser history. If not provided, a new `createBrowserHistory` instance will be created and used.\n\n### `stringifySearch` method\n\n- Type: `(search: Record<string, any>) => string`\n- Optional\n- A function that will be used to stringify search params when generating links.\n- Defaults to `defaultStringifySearch`.\n\n### `parseSearch` method\n\n- Type: `(search: string) => Record<string, any>`\n- Optional\n- A function that will be used to parse search params when parsing the current location.\n- Defaults to `defaultParseSearch`.\n\n### `search.strict` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- Configures how unknown search params (= not returned by any `validateSearch`) are treated.\n- If `false`, unknown search params will be kept.\n- If `true`, unknown search params will be removed.\n\n### `defaultPreload` property\n\n- Type: `undefined | false | 'intent' | 'viewport' | 'render'`\n- Optional\n- Defaults to `false`\n- If `false`, routes will not be preloaded by default in any way.\n- If `'intent'`, routes will be preloaded by default when the user hovers over a link or a `touchstart` event is detected on a `<Link>`.\n- If `'viewport'`, routes will be preloaded by default when they are within the viewport of the browser.\n- If `'render'`, routes will be preloaded by default as soon as they are rendered in the DOM.\n\n### `defaultPreloadDelay` property\n\n- Type: `number`\n- Optional\n- Defaults to `50`\n- The delay in milliseconds that a route must be hovered over or touched before it is preloaded.\n\n### `defaultComponent` property\n\n- Type: `RouteComponent`\n- Optional\n- Defaults to `Outlet`\n- The default `component` a route should use if no component is provided.\n\n### `defaultErrorComponent` property\n\n- Type: `RouteComponent`\n- Optional\n- Defaults to `ErrorComponent`\n- The default `errorComponent` a route should use if no error component is provided.\n\n### `defaultNotFoundComponent` property\n\n- Type: `NotFoundRouteComponent`\n- Optional\n- Defaults to `NotFound`\n- The default `notFoundComponent` a route should use if no notFound component is provided.\n\n### `defaultPendingComponent` property\n\n- Type: `RouteComponent`\n- Optional\n- The default `pendingComponent` a route should use if no pending component is provided.\n\n### `defaultPendingMs` property\n\n- Type: `number`\n- Optional\n- Defaults to `1000`\n- The default `pendingMs` a route should use if no pendingMs is provided.\n\n### `defaultPendingMinMs` property\n\n- Type: `number`\n- Optional\n- Defaults to `500`\n- The default `pendingMinMs` a route should use if no pendingMinMs is provided.\n\n### `defaultStaleTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `0`\n- The default `staleTime` a route should use if no staleTime is provided.\n\n### `defaultPreloadStaleTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `30_000` ms (30 seconds)\n- The default `preloadStaleTime` a route should use if no preloadStaleTime is provided.\n\n### `defaultPreloadGcTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes.\n- The default `preloadGcTime` a route should use if no preloadGcTime is provided.\n\n### `defaultGcTime` property\n\n- Type: `number`\n- Optional\n- Defaults to 30 minutes.\n- The default `gcTime` a route should use if no gcTime is provided.\n\n### `defaultOnCatch` property\n\n- Type: `(error: Error, errorInfo: ErrorInfo) => void`\n- Optional\n- The default `onCatch` handler for errors caught by the Router ErrorBoundary\n\n### `disableGlobalCatchBoundary` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- When `true`, disables the global catch boundary that normally wraps all route matches. This allows unhandled errors to bubble up to top-level error handlers in the browser.\n- Useful for testing tools, error reporting services, and debugging scenarios.\n\n### `defaultViewTransition` property\n\n- Type: `boolean | ViewTransitionOptions`\n- Optional\n- If `true`, route navigations will be called using `document.startViewTransition()`.\n- If [`ViewTransitionOptions`](../ViewTransitionOptionsType.md), route navigations will be called using `document.startViewTransition({update, types})`\n where `types` will be the strings array passed with `ViewTransitionOptions[\"types\"]`. If the browser does not support viewTransition types,\n the navigation will fall back to normal `document.startTransition()`, same as if `true` was passed.\n- If the browser does not support this api, this option will be ignored.\n- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.\n- See [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types) for more information on viewTransition types\n\n### `defaultHashScrollIntoView` property\n\n- Type: `boolean | ScrollIntoViewOptions`\n- Optional\n- Defaults to `true` so the element with an id matching the hash will be scrolled into view after the location is committed to history.\n- If `false`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.\n- If an object is provided, it will be passed to the `scrollIntoView` method as options.\n- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on `ScrollIntoViewOptions`.\n\n### `caseSensitive` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- If `true`, all routes will be matched as case-sensitive.\n\n### `basepath` property\n\n- Type: `string`\n- Optional\n- Defaults to `/`\n- The basepath for the entire router. This is useful for mounting a router instance at a subpath.\n\n### `context` property\n\n- Type: `any`\n- Optional or required if the root route was created with [`createRootRouteWithContext()`](../createRootRouteWithContextFunction.md).\n- The root context that will be provided to all routes in the route tree. This can be used to provide a context to all routes in the tree without having to provide it to each route individually.\n\n### `dehydrate` method\n\n- Type: `() => TDehydrated`\n- Optional\n- A function that will be called when the router is dehydrated. The return value of this function will be serialized and stored in the router's dehydrated state.\n\n### `hydrate` method\n\n- Type: `(dehydrated: TDehydrated) => void`\n- Optional\n- A function that will be called when the router is hydrated. The return value of this function will be serialized and stored in the router's dehydrated state.\n\n### `routeMasks` property\n\n- Type: `RouteMask[]`\n- Optional\n- An array of route masks that will be used to mask routes in the route tree. Route masking is when you display a route at a different path than the one it is configured to match, like a modal popup that when shared will unmask to the modal's content instead of the modal's context.\n\n### `unmaskOnReload` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- If `true`, route masks will, by default, be removed when the page is reloaded. This can be overridden on a per-mask basis by setting the `unmaskOnReload` option on the mask, or on a per-navigation basis by setting the `unmaskOnReload` option in the `Navigate` options.\n\n### `Wrap` property\n\n- Type: `React.Component`\n- Optional\n- A component that will be used to wrap the entire router. This is useful for providing a context to the entire router. Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.\n\n**Example**\n\n```tsx\nimport { createRouter } from '@tanstack/react-router'\n\nconst router = createRouter({\n // ...\n Wrap: ({ children }) => {\n return <MyContext.Provider value={myContext}>{children}</MyContext>\n },\n})\n```\n\n### `InnerWrap` property\n\n- Type: `React.Component`\n- Optional\n- A component that will be used to wrap the inner contents of the router. This is useful for providing a context to the inner contents of the router where you also need access to the router context and hooks. Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.\n\n**Example**\n\n```tsx\nimport { createRouter } from '@tanstack/react-router'\n\nconst router = createRouter({\n // ...\n InnerWrap: ({ children }) => {\n const routerState = useRouterState()\n\n return (\n <MyContext.Provider value={myContext}>\n {children}\n </MyContext>\n )\n },\n})\n```\n\n### `notFoundMode` property\n\n- Type: `'root' | 'fuzzy'`\n- Optional\n- Defaults to `'fuzzy'`\n- This property controls how TanStack Router will handle scenarios where it cannot find a route to match the current location. See the [Not Found Errors guide](../../../guide/not-found-errors.md) for more information.\n\n### `notFoundRoute` property\n\n- **Deprecated**\n- Type: `NotFoundRoute`\n- Optional\n- A route that will be used as the default not found route for every branch of the route tree. This can be overridden on a per-branch basis by providing a not found route to the `NotFoundRoute` option on the root route of the branch.\n\n### `trailingSlash` property\n\n- Type: `'always' | 'never' | 'preserve'`\n- Optional\n- Defaults to `never`\n- Configures how trailing slashes are treated. `'always'` will add a trailing slash if not present, `'never'` will remove the trailing slash if present and `'preserve'` will not modify the trailing slash.\n\n### `pathParamsAllowedCharacters` property\n\n- Type: `Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>`\n- Optional\n- Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent.\n\n### `defaultStructuralSharing` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- Configures whether structural sharing is enabled by default for fine-grained selectors.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n### `defaultRemountDeps` property\n\n- Type:\n\n```tsx\ntype defaultRemountDeps = (opts: RemountDepsOptions) => any\n\ninterface RemountDepsOptions<\n in out TRouteId,\n in out TFullSearchSchema,\n in out TAllParams,\n in out TLoaderDeps,\n> {\n routeId: TRouteId\n search: TFullSearchSchema\n params: TAllParams\n loaderDeps: TLoaderDeps\n}\n```\n\n- Optional\n- A default function that will be called to determine whether a route component shall be remounted after navigation. If this function returns a different value than previously, it will remount.\n- The return value needs to be JSON serializable.\n- By default, a route component will not be remounted if it stays active after a navigation\n\nExample: \nIf you want to configure to remount all route components upon `params` change, use:\n\n```tsx\nremountDeps: ({ params }) => params\n```\n\n# RouterState type\n\nThe `RouterState` type represents shape of the internal state of the router. The Router's internal state is useful, if you need to access certain internals of the router, such as any pending matches, is the router in its loading state, etc.\n\n```tsx\ntype RouterState = {\n status: 'pending' | 'idle'\n isLoading: boolean\n isTransitioning: boolean\n matches: Array<RouteMatch>\n pendingMatches: Array<RouteMatch>\n location: ParsedLocation\n resolvedLocation: ParsedLocation\n}\n```\n\n## RouterState properties\n\nThe `RouterState` type contains all of the properties that are available on the router state.\n\n### `status` property\n\n- Type: `'pending' | 'idle'`\n- The current status of the router. If the router is pending, it means that it is currently loading a route or the router is still transitioning to the new route.\n\n### `isLoading` property\n\n- Type: `boolean`\n- `true` if the router is currently loading a route or waiting for a route to finish loading.\n\n### `isTransitioning` property\n\n- Type: `boolean`\n- `true` if the router is currently transitioning to a new route.\n\n### `matches` property\n\n- Type: [`Array<RouteMatch>`](../RouteMatchType.md)\n- An array of all of the route matches that have been resolved and are currently active.\n\n### `pendingMatches` property\n\n- Type: [`Array<RouteMatch>`](../RouteMatchType.md)\n- An array of all of the route matches that are currently pending.\n\n### `location` property\n\n- Type: [`ParsedLocation`](../ParsedLocationType.md)\n- The latest location that the router has parsed from the browser history. This location may not be resolved and loaded yet.\n\n### `resolvedLocation` property\n\n- Type: [`ParsedLocation`](../ParsedLocationType.md)\n- The location that the router has resolved and loaded.\n\n# Router type\n\nThe `Router` type is used to describe a router instance.\n\n## `Router` properties and methods\n\nAn instance of the `Router` has the following properties and methods:\n\n### `.update` method\n\n- Type: `(newOptions: RouterOptions) => void`\n- Updates the router instance with new options.\n\n### `state` property\n\n- Type: [`RouterState`](../RouterStateType.md)\n- The current state of the router.\n\n> \u26A0\uFE0F\u26A0\uFE0F\u26A0\uFE0F **`router.state` is always up to date, but NOT REACTIVE. If you use `router.state` in a component, the component will not re-render when the router state changes. To get a reactive version of the router state, use the [`useRouterState`](../useRouterStateHook.md) hook.**\n\n### `.subscribe` method\n\n- Type: `(eventType: TType, fn: ListenerFn<RouterEvents[TType]>) => (event: RouterEvent) => void`\n- Subscribes to a [`RouterEvent`](../RouterEventsType.md).\n- Returns a function that can be used to unsubscribe from the event.\n- The callback provided to the returned function will be called with the event that was emitted.\n\n### `.matchRoutes` method\n\n- Type: `(pathname: string, locationSearch?: Record<string, any>, opts?: { throwOnError?: boolean; }) => RouteMatch[]`\n- Matches a pathname and search params against the router's route tree and returns an array of route matches.\n- If `opts.throwOnError` is `true`, any errors that occur during the matching process will be thrown (in addition to being returned in the route match's `error` property).\n\n### `.cancelMatch` method\n\n- Type: `(matchId: string) => void`\n- Cancels a route match that is currently pending by calling `match.abortController.abort()`.\n\n### `.cancelMatches` method\n\n- Type: `() => void`\n- Cancels all route matches that are currently pending by calling `match.abortController.abort()` on each one.\n\n### `.buildLocation` method\n\nBuilds a new parsed location object that can be used later to navigate to a new location.\n\n- Type: `(opts: BuildNextOptions) => ParsedLocation`\n- Properties\n - `from`\n - Type: `string`\n - Optional\n - The path to navigate from. If not provided, the current path will be used.\n - `to`\n - Type: `string | number | null`\n - Optional\n - The path to navigate to. If `null`, the current path will be used.\n - `params`\n - Type: `true | Updater<unknown>`\n - Optional\n - If `true`, the current params will be used. If a function is provided, it will be called with the current params and the return value will be used.\n - `search`\n - Type: `true | Updater<unknown>`\n - Optional\n - If `true`, the current search params will be used. If a function is provided, it will be called with the current search params and the return value will be used.\n - `hash`\n - Type: `true | Updater<string>`\n - Optional\n - If `true`, the current hash will be used. If a function is provided, it will be called with the current hash and the return value will be used.\n - `state`\n - Type: `true | NonNullableUpdater<ParsedHistoryState, HistoryState>`\n - Optional\n - If `true`, the current state will be used. If a function is provided, it will be called with the current state and the return value will be used.\n - `mask`\n - Type: `object`\n - Optional\n - Contains all of the same BuildNextOptions, with the addition of `unmaskOnReload`.\n - `unmaskOnReload`\n - Type: `boolean`\n - Optional\n - If `true`, the route mask will be removed when the page is reloaded. This can be overridden on a per-navigation basis by setting the `unmaskOnReload` option in the `Navigate` options.\n\n### `.commitLocation` method\n\nCommits a new location object to the browser history.\n\n- Type\n ```tsx\n type commitLocation = (\n location: ParsedLocation & {\n replace?: boolean\n resetScroll?: boolean\n hashScrollIntoView?: boolean | ScrollIntoViewOptions\n ignoreBlocker?: boolean\n },\n ) => Promise<void>\n ```\n- Properties\n - `location`\n - Type: [`ParsedLocation`](../ParsedLocationType.md)\n - Required\n - The location to commit to the browser history.\n - `replace`\n - Type: `boolean`\n - Optional\n - Defaults to `false`.\n - If `true`, the location will be committed to the browser history using `history.replace` instead of `history.push`.\n - `resetScroll`\n - Type: `boolean`\n - Optional\n - Defaults to `true` so that the scroll position will be reset to 0,0 after the location is committed to the browser history.\n - If `false`, the scroll position will not be reset to 0,0 after the location is committed to history.\n - `hashScrollIntoView`\n - Type: `boolean | ScrollIntoViewOptions`\n - Optional\n - Defaults to `true` so the element with an id matching the hash will be scrolled into view after the location is committed to history.\n - If `false`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.\n - If an object is provided, it will be passed to the `scrollIntoView` method as options.\n - See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on `ScrollIntoViewOptions`.\n - `ignoreBlocker`\n - Type: `boolean`\n - Optional\n - Defaults to `false`.\n - If `true`, navigation will ignore any blockers that might prevent it.\n\n### `.navigate` method\n\nNavigates to a new location.\n\n- Type\n ```tsx\n type navigate = (options: NavigateOptions) => Promise<void>\n ```\n\n### `.invalidate` method\n\nInvalidates route matches by forcing their `beforeLoad` and `load` functions to be called again.\n\n- Type: `(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean, sync?: boolean, forcePending?: boolean }) => Promise<void>`\n- This is useful any time your loader data might be out of date or stale. For example, if you have a route that displays a list of posts, and you have a loader function that fetches the list of posts from an API, you might want to invalidate the route matches for that route any time a new post is created so that the list of posts is always up-to-date.\n- if `filter` is not supplied, all matches will be invalidated\n- if `filter` is supplied, only matches for which `filter` returns `true` will be invalidated.\n- if `sync` is true, the promise returned by this function will only resolve once all loaders have finished.\n- if `forcePending` is true, the invalidated matches will be put into `'pending'` state regardless whether they are in `'error'` state or not.\n- You might also want to invalidate the Router if you imperatively `reset` the router's `CatchBoundary` to trigger loaders again.\n\n### `.clearCache` method\n\nRemove cached route matches.\n\n- Type: `(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean}) => void`\n- if `filter` is not supplied, all cached matches will be removed\n- if `filter` is supplied, only matches for which `filter` returns `true` will be removed.\n\n### `.load` method\n\nLoads all of the currently matched route matches and resolves when they are all loaded and ready to be rendered.\n\n> \u26A0\uFE0F\u26A0\uFE0F\u26A0\uFE0F **`router.load()` respects `route.staleTime` and will not forcefully reload a route match if it is still fresh. If you need to forcefully reload a route match, use `router.invalidate()` instead.**\n\n- Type: `(opts?: {sync?: boolean}) => Promise<void>`\n- if `sync` is true, the promise returned by this function will only resolve once all loaders have finished.\n- The most common use case for this method is to call it when doing SSR to ensure that all of the critical data for the current route is loaded before attempting to stream or render the application to the client.\n\n### `.preloadRoute` method\n\nPreloads all of the matches that match the provided `NavigateOptions`.\n\n> \u26A0\uFE0F\u26A0\uFE0F\u26A0\uFE0F **Preloaded route matches are not stored long-term in the router state. They are only stored until the next attempted navigation action.**\n\n- Type: `(opts?: NavigateOptions) => Promise<RouteMatch[]>`\n- Properties\n - `opts`\n - Type: `NavigateOptions`\n - Optional, defaults to the current location.\n - The options that will be used to determine which route matches to preload.\n- Returns\n - A promise that resolves with an array of all of the route matches that were preloaded.\n\n### `.loadRouteChunk` method\n\nLoads the JS chunk of the route.\n\n- Type: `(route: AnyRoute) => Promise<void>`\n\n### `.matchRoute` method\n\nMatches a pathname and search params against the router's route tree and returns a route match's params or false if no match was found.\n\n- Type: `(dest: ToOptions, matchOpts?: MatchRouteOptions) => RouteMatch['params'] | false`\n- Properties\n - `dest`\n - Type: `ToOptions`\n - Required\n - The destination to match against.\n - `matchOpts`\n - Type: `MatchRouteOptions`\n - Optional\n - Options that will be used to match the destination.\n- Returns\n - A route match's params if a match was found.\n - `false` if no match was found.\n\n### `.dehydrate` method\n\nDehydrates the router's critical state into a serializable object that can be sent to the client in an initial request.\n\n- Type: `() => DehydratedRouter`\n- Returns\n - A serializable object that contains the router's critical state.\n\n### `.hydrate` method\n\nHydrates the router's critical state from a serializable object that was sent from the server in an initial request.\n\n- Type: `(dehydrated: DehydratedRouter) => void`\n- Properties\n - `dehydrated`\n - Type: `DehydratedRouter`\n - Required\n - The dehydrated router state that was sent from the server.\n\n# ToMaskOptions type\n\nThe `ToMaskOptions` type extends the [`ToOptions`](../ToOptionsType.md) type and describes additional options available when using route masks.\n\n```tsx\ntype ToMaskOptions = ToOptions & {\n unmaskOnReload?: boolean\n}\n```\n\n- [`ToOptions`](../ToOptionsType.md)\n\n# ToOptions type\n\nThe `ToOptions` type contains several properties that can be used to describe a router destination.\n\n```tsx\ntype ToOptions = {\n from?: ValidRoutePath | string\n to?: ValidRoutePath | string\n hash?: true | string | ((prev?: string) => string)\n state?: true | HistoryState | ((prev: HistoryState) => HistoryState)\n} & SearchParamOptions &\n PathParamOptions\n\ntype SearchParamOptions = {\n search?: true | TToSearch | ((prev: TFromSearch) => TToSearch)\n}\n\ntype PathParamOptions = {\n path?: true | Record<string, TPathParam> | ((prev: TFromParams) => TToParams)\n}\n```\n\n# UseMatchRouteOptions type\n\nThe `UseMatchRouteOptions` type extends the [`ToOptions`](../ToOptionsType.md) type and describes additional options available when using the [`useMatchRoute`](../useMatchRouteHook.md) hook.\n\n```tsx\nexport type UseMatchRouteOptions = ToOptions & MatchRouteOptions\n```\n\n- [`ToOptions`](../ToOptionsType.md)\n- [`MatchRouteOptions`](../MatchRouteOptionsType.md)\n\n# ViewTransitionOptions type\n\nThe `ViewTransitionOptions` type is used to define a\n[viewTransition type](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types).\n\n```tsx\ninterface ViewTransitionOptions {\n types: Array<string>\n}\n```\n\n## ViewTransitionOptions properties\n\nThe `ViewTransitionOptions` type accepts an object with a single property:\n\n### `types` property\n\n- Type: `Array<string>`\n- Required\n- The types array that will be passed to the `document.startViewTransition({update, types}) call`;\n\n# Await component\n\nThe `Await` component is a component that suspends until the provided promise is resolved or rejected.\nThis is only necessary for React 18.\nIf you are using React 19, you can use the `use()` hook instead.\n\n## Await props\n\nThe `Await` component accepts the following props:\n\n### `props.promise` prop\n\n- Type: `Promise<T>`\n- Required\n- The promise to await.\n\n### `props.children` prop\n\n- Type: `(result: T) => React.ReactNode`\n- Required\n- A function that will be called with the resolved value of the promise.\n\n## Await returns\n\n- Throws an error if the promise is rejected.\n- Suspends (throws a promise) if the promise is pending.\n- Returns the resolved value of a deferred promise if the promise is resolved using `props.children` as the render function.\n\n## Examples\n\n```tsx\nimport { Await } from '@tanstack/react-router'\n\nfunction Component() {\n const { deferredPromise } = route.useLoaderData()\n\n return (\n <Await promise={deferredPromise}>\n {(data) => <div>{JSON.stringify(data)}</div>}\n </Await>\n )\n}\n```\n\n# CatchBoundary component\n\nThe `CatchBoundary` component is a component that catches errors thrown by its children, renders an error component and optionally calls the `onCatch` callback. It also accepts a `getResetKey` function that can be used to declaratively reset the component's state when the key changes.\n\n## CatchBoundary props\n\nThe `CatchBoundary` component accepts the following props:\n\n### `props.getResetKey` prop\n\n- Type: `() => string`\n- Required\n- A function that returns a string that will be used to reset the component's state when the key changes.\n\n### `props.children` prop\n\n- Type: `React.ReactNode`\n- Required\n- The component's children to render when there is no error\n\n### `props.errorComponent` prop\n\n- Type: `React.ReactNode`\n- Optional - [`default: ErrorComponent`](../errorComponentComponent.md)\n- The component to render when there is an error.\n\n### `props.onCatch` prop\n\n- Type: `(error: any) => void`\n- Optional\n- A callback that will be called with the error that was thrown by the component's children.\n\n## CatchBoundary returns\n\n- Returns the component's children if there is no error.\n- Returns the `errorComponent` if there is an error.\n\n## Examples\n\n```tsx\nimport { CatchBoundary } from '@tanstack/react-router'\n\nfunction Component() {\n return (\n <CatchBoundary\n getResetKey={() => 'reset'}\n onCatch={(error) => console.error(error)}\n >\n <div>My Component</div>\n </CatchBoundary>\n )\n}\n```\n\n# CatchNotFound Component\n\nThe `CatchNotFound` component is a component that catches not-found errors thrown by its children, renders a fallback component and optionally calls the `onCatch` callback. It resets when the pathname changes.\n\n## CatchNotFound props\n\nThe `CatchNotFound` component accepts the following props:\n\n### `props.children` prop\n\n- Type: `React.ReactNode`\n- Required\n- The component's children to render when there is no error\n\n### `props.fallback` prop\n\n- Type: `(error: NotFoundError) => React.ReactElement`\n- Optional\n- The component to render when there is an error\n\n### `props.onCatch` prop\n\n- Type: `(error: any) => void`\n- Optional\n- A callback that will be called with the error that was thrown by the component's children\n\n## CatchNotFound returns\n\n- Returns the component's children if there is no error.\n- Returns the `fallback` if there is an error.\n\n## Examples\n\n```tsx\nimport { CatchNotFound } from '@tanstack/react-router'\n\nfunction Component() {\n return (\n <CatchNotFound\n fallback={(error) => <p>Not found error! {JSON.stringify(error)}</p>}\n >\n <ComponentThatMightThrowANotFoundError />\n </CatchNotFound>\n )\n}\n```\n\n# ClientOnly Component\n\nThe `ClientOnly` component is used to render a components only in the client, without breaking the server-side rendering due to hydration errors. It accepts a `fallback` prop that will be rendered if the JS is not yet loaded in the client.\n\n## Props\n\nThe `ClientOnly` component accepts the following props:\n\n### `props.fallback` prop\n\nThe fallback component to render if the JS is not yet loaded in the client.\n\n### `props.children` prop\n\nThe component to render if the JS is loaded in the client.\n\n## Returns\n\n- Returns the component's children if the JS is loaded in the client.\n- Returns the `fallback` component if the JS is not yet loaded in the client.\n\n## Examples\n\n```tsx\n// src/routes/dashboard.tsx\nimport { ClientOnly, createFileRoute } from '@tanstack/react-router'\nimport {\n Charts,\n FallbackCharts,\n} from './charts-that-break-server-side-rendering'\n\nexport const Route = createFileRoute('/dashboard')({\n component: Dashboard,\n // ... other route options\n})\n\nfunction Dashboard() {\n return (\n <div>\n <p>Dashboard</p>\n <ClientOnly fallback={<FallbackCharts />}>\n <Charts />\n </ClientOnly>\n </div>\n )\n}\n```\n\n# createFileRoute function\n\nThe `createFileRoute` function is a factory that can be used to create a file-based route instance. This route instance can then be used to automatically generate a route tree with the `tsr generate` and `tsr watch` commands.\n\n## createFileRoute options\n\nThe `createFileRoute` function accepts a single argument of type `string` that represents the `path` of the file that the route will be generated from.\n\n### `path` option\n\n- Type: `string` literal\n- Required, but **automatically inserted and updated by the `tsr generate` and `tsr watch` commands**\n- The full path of the file that the route will be generated from\n\n## createFileRoute returns\n\nA new function that accepts a single argument of type [`RouteOptions`](../RouteOptionsType.md) that will be used to configure the file [`Route`](../RouteType.md) instance.\n\n> \u26A0\uFE0F Note: For `tsr generate` and `tsr watch` to work properly, the file route instance must be exported from the file using the `Route` identifier.\n\n## Examples\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n loader: () => {\n return 'Hello World'\n },\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# createLazyFileRoute function\n\nThe `createLazyFileRoute` function is used for creating a partial file-based route route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as `component`, `pendingComponent`, `errorComponent`, and the `notFoundComponent`.\n\n## createLazyFileRoute options\n\nThe `createLazyFileRoute` function accepts a single argument of type `string` that represents the `path` of the file that the route will be generated from.\n\n### `path`\n\n- Type: `string`\n- Required, but **automatically inserted and updated by the `tsr generate` and `tsr watch` commands**\n- The full path of the file that the route will be generated from.\n\n### createLazyFileRoute returns\n\nA new function that accepts a single argument of partial of the type [`RouteOptions`](../RouteOptionsType.md) that will be used to configure the file [`Route`](../RouteType.md) instance.\n\n- Type:\n\n```tsx\nPick<\n RouteOptions,\n 'component' | 'pendingComponent' | 'errorComponent' | 'notFoundComponent'\n>\n```\n\n- [`RouteOptions`](../RouteOptionsType.md)\n\n> \u26A0\uFE0F Note: For `tsr generate` and `tsr watch` to work properly, the file route instance must be exported from the file using the `Route` identifier.\n\n### Examples\n\n```tsx\nimport { createLazyFileRoute } from '@tanstack/react-router'\n\nexport const Route = createLazyFileRoute('/')({\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# createLazyRoute function\n\nThe `createLazyRoute` function is used for creating a partial code-based route route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as `component`, `pendingComponent`, `errorComponent`, and the `notFoundComponent`.\n\n## createLazyRoute options\n\nThe `createLazyRoute` function accepts a single argument of type `string` that represents the `id` of the route.\n\n### `id`\n\n- Type: `string`\n- Required\n- The route id of the route.\n\n### createLazyRoute returns\n\nA new function that accepts a single argument of partial of the type [`RouteOptions`](../RouteOptionsType.md) that will be used to configure the file [`Route`](../RouteType.md) instance.\n\n- Type:\n\n```tsx\nPick<\n RouteOptions,\n 'component' | 'pendingComponent' | 'errorComponent' | 'notFoundComponent'\n>\n```\n\n- [`RouteOptions`](../RouteOptionsType.md)\n\n> \u26A0\uFE0F Note: This route instance must be manually lazily loaded against its critical route instance using the `lazy` method returned by the `createRoute` function.\n\n### Examples\n\n```tsx\n// src/route-pages/index.tsx\nimport { createLazyRoute } from '@tanstack/react-router'\n\nexport const Route = createLazyRoute('/')({\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n\n// src/routeTree.tsx\nimport {\n createRootRouteWithContext,\n createRoute,\n Outlet,\n} from '@tanstack/react-router'\n\ninterface MyRouterContext {\n foo: string\n}\n\nconst rootRoute = createRootRouteWithContext<MyRouterContext>()({\n component: () => <Outlet />,\n})\n\nconst indexRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/',\n}).lazy(() => import('./route-pages/index').then((d) => d.Route))\n\nexport const routeTree = rootRoute.addChildren([indexRoute])\n```\n\n# createRootRoute function\n\nThe `createRootRoute` function returns a new root route instance. A root route instance can then be used to create a route-tree.\n\n## createRootRoute options\n\nThe options that will be used to configure the root route instance.\n\n- Type:\n\n```tsx\nOmit<\n RouteOptions,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n>\n```\n\n- [`RouteOptions`](../RouteOptionsType.md)\n- Optional\n\n## createRootRoute returns\n\nA new [`Route`](../RouteType.md) instance.\n\n## Examples\n\n```tsx\nimport { createRootRoute, createRouter, Outlet } from '@tanstack/react-router'\n\nconst rootRoute = createRootRoute({\n component: () => <Outlet />,\n // ... root route options\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst router = createRouter({\n routeTree,\n})\n```\n\n# createRootRouteWithContext function\n\nThe `createRootRouteWithContext` function is a helper function that can be used to create a root route instance that requires a context type to be fulfilled when the router is created.\n\n## createRootRouteWithContext generics\n\nThe `createRootRouteWithContext` function accepts a single generic argument:\n\n### `TRouterContext` generic\n\n- Type: `TRouterContext`\n- Optional, **but recommended**.\n- The context type that will be required to be fulfilled when the router is created\n\n## createRootRouteWithContext returns\n\n- A factory function that can be used to create a new [`createRootRoute`](../createRootRouteFunction.md) instance.\n- It accepts a single argument, the same as the [`createRootRoute`](../createRootRouteFunction.md) function.\n\n## Examples\n\n```tsx\nimport {\n createRootRouteWithContext,\n createRouter,\n} from '@tanstack/react-router'\nimport { QueryClient } from '@tanstack/react-query'\n\ninterface MyRouterContext {\n queryClient: QueryClient\n}\n\nconst rootRoute = createRootRouteWithContext<MyRouterContext>()({\n component: () => <Outlet />,\n // ... root route options\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst queryClient = new QueryClient()\n\nconst router = createRouter({\n routeTree,\n context: {\n queryClient,\n },\n})\n```\n\n# createRoute function\n\nThe `createRoute` function implements returns a [`Route`](../RouteType.md) instance. A route instance can then be passed to a root route's children to create a route tree, which is then passed to the router.\n\n## createRoute options\n\n- Type: [`RouteOptions`](../RouteOptionsType.md)\n- Required\n- The options that will be used to configure the route instance\n\n## createRoute returns\n\nA new [`Route`](../RouteType.md) instance.\n\n## Examples\n\n```tsx\nimport { createRoute } from '@tanstack/react-router'\nimport { rootRoute } from './__root'\n\nconst Route = createRoute({\n getParentRoute: () => rootRoute,\n path: '/',\n loader: () => {\n return 'Hello World'\n },\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# createRouteMask function\n\nThe `createRouteMask` function is a helper function that can be used to create a route mask configuration that can be passed to the `RouterOptions.routeMasks` option.\n\n## createRouteMask options\n\n- Type: [`RouteMask`](../RouteMaskType.md)\n- Required\n- The options that will be used to configure the route mask\n\n## createRouteMask returns\n\n- A object with the type signature of [`RouteMask`](../RouteMaskType.md) that can be passed to the `RouterOptions.routeMasks` option.\n\n## Examples\n\n```tsx\nimport { createRouteMask, createRouter } from '@tanstack/react-router'\n\nconst photoModalToPhotoMask = createRouteMask({\n routeTree,\n from: '/photos/$photoId/modal',\n to: '/photos/$photoId',\n params: true,\n})\n\n// Set up a Router instance\nconst router = createRouter({\n routeTree,\n routeMasks: [photoModalToPhotoMask],\n})\n```\n\n# createRouter function\n\nThe `createRouter` function accepts a [`RouterOptions`](../RouterOptionsType.md) object and creates a new [`Router`](../RouterClass.md) instance.\n\n## createRouter options\n\n- Type: [`RouterOptions`](../RouterOptionsType.md)\n- Required\n- The options that will be used to configure the router instance.\n\n## createRouter returns\n\n- An instance of the [`Router`](../RouterType.md).\n\n## Examples\n\n```tsx\nimport { createRouter, RouterProvider } from '@tanstack/react-router'\nimport { routeTree } from './routeTree.gen'\n\nconst router = createRouter({\n routeTree,\n defaultPreload: 'intent',\n})\n\nexport default function App() {\n return <RouterProvider router={router} />\n}\n```\n\n# DefaultGlobalNotFound component\n\nThe `DefaultGlobalNotFound` component is a component that renders \"Not Found\" on the root route when there is no other route that matches and a `notFoundComponent` is not provided.\n\n## DefaultGlobalNotFound returns\n\n```tsx\n<p>Not Found</p>\n```\n\n# defer function\n\n> [!CAUTION]\n> You don't need to call `defer` manually anymore, Promises are handled automatically now.\n\nThe `defer` function wraps a promise with a deferred state object that can be used to inspect the promise's state. This deferred promise can then be passed to the [`useAwaited`](../useAwaitedHook.md) hook or the [`<Await>`](../awaitComponent.md) component for suspending until the promise is resolved or rejected.\n\nThe `defer` function accepts a single argument, the `promise` to wrap with a deferred state object.\n\n## defer options\n\n- Type: `Promise<T>`\n- Required\n- The promise to wrap with a deferred state object.\n\n## defer returns\n\n- A promise that can be passed to the [`useAwaited`](../useAwaitedHook.md) hook or the [`<Await>`](../awaitComponent.md) component.\n\n## Examples\n\n```tsx\nimport { defer } from '@tanstack/react-router'\n\nconst route = createRoute({\n loader: () => {\n const deferredPromise = defer(fetch('/api/data'))\n return { deferredPromise }\n },\n component: MyComponent,\n})\n\nfunction MyComponent() {\n const { deferredPromise } = Route.useLoaderData()\n\n const data = useAwaited({ promise: deferredPromise })\n\n // or\n\n return (\n <Await promise={deferredPromise}>\n {(data) => <div>{JSON.stringify(data)}</div>}\n </Await>\n )\n}\n```\n\n# ErrorComponent component\n\nThe `ErrorComponent` component is a component that renders an error message and optionally the error's message.\n\n## ErrorComponent props\n\nThe `ErrorComponent` component accepts the following props:\n\n### `props.error` prop\n\n- Type: `TError` (defaults to `Error`)\n- The error that was thrown by the component's children\n\n### `props.info` prop\n\n- Type: `{ componentStack: string }`\n- Optional\n- Additional information about where the error was thrown, such as the React component stack trace.\n\n### `props.reset` prop\n\n- Type: `() => void`\n- A function to programmatically reset the error state\n\n## ErrorComponent returns\n\n- Returns a formatted error message with the error's message if it exists.\n- The error message can be toggled by clicking the \"Show Error\" button.\n- By default, the error message will be shown in development.\n\n# getRouteApi function\n\nThe `getRouteApi` function provides type-safe version of common hooks like `useParams`, `useSearch`, `useRouteContext`, `useNavigate`, `useLoaderData`, and `useLoaderDeps` that are pre-bound to a specific route ID and corresponding registered route types.\n\n## getRouteApi options\n\nThe `getRouteApi` function accepts a single argument, a `routeId` string literal.\n\n### `routeId` option\n\n- Type: `string`\n- Required\n- The route ID to which the [`RouteApi`](../RouteApiClass.md) instance will be bound\n\n## getRouteApi returns\n\n- An instance of the [`RouteApi`](../RouteApiType.md) that is pre-bound to the route ID that the `getRouteApi` function was called with.\n\n## Examples\n\n```tsx\nimport { getRouteApi } from '@tanstack/react-router'\n\nconst routeApi = getRouteApi('/posts')\n\nexport function PostsPage() {\n const posts = routeApi.useLoaderData()\n // ...\n}\n```\n\n# HistoryState interface\n\nThe `HistoryState` interface is an interface exported by the `history` package that describes the shape of the state object that can be used in conjunction with the `history` package and the `window.location` API.\n\nYou can extend this interface to add additional properties to the state object across your application.\n\n```tsx\n// src/main.tsx\ndeclare module '@tanstack/react-router' {\n // ...\n\n interface HistoryState {\n additionalRequiredProperty: number\n additionalProperty?: string\n }\n}\n```\n\n# isNotFound function\n\nThe `isNotFound` function can be used to determine if an object is a [`NotFoundError`](../NotFoundErrorType.md) object.\n\n## isNotFound options\n\nThe `isNotFound` function accepts a single argument, an `input`.\n\n### `input` option\n\n- Type: `unknown`\n- Required\n- An object to check if it is a [`NotFoundError`](../NotFoundErrorType.md).\n\n## isNotFound returns\n\n- Type: `boolean`\n- `true` if the object is a [`NotFoundError`](../NotFoundErrorType.md).\n- `false` if the object is not a [`NotFoundError`](../NotFoundErrorType.md).\n\n## Examples\n\n```tsx\nimport { isNotFound } from '@tanstack/react-router'\n\nfunction somewhere(obj: unknown) {\n if (isNotFound(obj)) {\n // ...\n }\n}\n```\n\n# isRedirect function\n\nThe `isRedirect` function can be used to determine if an object is a redirect object.\n\n## isRedirect options\n\nThe `isRedirect` function accepts a single argument, an `input`.\n\n#### `input`\n\n- Type: `unknown`\n- Required\n- An object to check if it is a redirect object\n\n## isRedirect returns\n\n- Type: `boolean`\n- `true` if the object is a redirect object\n- `false` if the object is not a redirect object\n\n## Examples\n\n```tsx\nimport { isRedirect } from '@tanstack/react-router'\n\nfunction somewhere(obj: unknown) {\n if (isRedirect(obj)) {\n // ...\n }\n}\n```\n\n# lazyRouteComponent function\n\n> [!IMPORTANT]\n> If you are using file-based routing, it's recommended to use the `createLazyFileRoute` function instead.\n\nThe `lazyRouteComponent` function can be used to create a one-off code-split route component that can be preloaded using a `component.preload()` method.\n\n## lazyRouteComponent options\n\nThe `lazyRouteComponent` function accepts two arguments:\n\n### `importer` option\n\n- Type: `() => Promise<T>`\n- Required\n- A function that returns a promise that resolves to an object that contains the component to be loaded.\n\n### `exportName` option\n\n- Type: `string`\n- Optional\n- The name of the component to be loaded from the imported object. Defaults to `'default'`.\n\n## lazyRouteComponent returns\n\n- A `React.lazy` component that can be preloaded using a `component.preload()` method.\n\n## Examples\n\n```tsx\nimport { lazyRouteComponent } from '@tanstack/react-router'\n\nconst route = createRoute({\n path: '/posts/$postId',\n component: lazyRouteComponent(() => import('./Post')), // default export\n})\n\n// or\n\nconst route = createRoute({\n path: '/posts/$postId',\n component: lazyRouteComponent(\n () => import('./Post'),\n 'PostByIdPageComponent', // named export\n ),\n})\n```\n\n# Link component\n\nThe `Link` component is a component that can be used to create a link that can be used to navigate to a new location. This includes changes to the pathname, search params, hash, and location state.\n\n## Link props\n\nThe `Link` component accepts the following props:\n\n### `...props`\n\n- Type: `LinkProps & React.RefAttributes<HTMLAnchorElement>`\n- [`LinkProps`](../LinkPropsType.md)\n\n## Link returns\n\nAn anchor element that can be used to navigate to a new location.\n\n## Examples\n\n```tsx\nimport { Link } from '@tanstack/react-router'\n\nfunction Component() {\n return (\n <Link\n to=\"/somewhere/$somewhereId\"\n params={{ somewhereId: 'baz' }}\n search={(prev) => ({ ...prev, foo: 'bar' })}\n >\n Click me\n </Link>\n )\n}\n```\n\n# Link options\n\n`linkOptions` is a function which type checks an object literal with the intention of being used for `Link`, `navigate` or `redirect`\n\n## linkOptions props\n\nThe `linkOptions` accepts the following option:\n\n### `...props`\n\n- Type: `LinkProps & React.RefAttributes<HTMLAnchorElement>`\n- [`LinkProps`](../LinkPropsType.md)\n\n## `linkOptions` returns\n\nAn object literal with the exact type inferred from the input\n\n## Examples\n\n```tsx\nconst userLinkOptions = linkOptions({\n to: '/dashboard/users/user',\n search: {\n usersView: {\n sortBy: 'email',\n filterBy: 'filter',\n },\n userId: 0,\n },\n})\n\nfunction DashboardComponent() {\n return <Link {...userLinkOptions} />\n}\n```\n\n# MatchRoute component\n\nA component version of the `useMatchRoute` hook. It accepts the same options as the `useMatchRoute` with additional props to aid in conditional rendering.\n\n## MatchRoute props\n\nThe `MatchRoute` component accepts the same options as the `useMatchRoute` hook with additional props to aid in conditional rendering.\n\n### `...props` prop\n\n- Type: [`UseMatchRouteOptions`](../UseMatchRouteOptionsType.md)\n\n### `children` prop\n\n- Optional\n- `React.ReactNode`\n - The component that will be rendered if the route is matched.\n- `((params: TParams | false) => React.ReactNode)`\n - A function that will be called with the matched route's params or `false` if no route was matched. This can be useful for components that need to always render, but render different props based on a route match or not.\n\n## MatchRoute returns\n\nEither the `children` prop or the return value of the `children` function.\n\n## Examples\n\n```tsx\nimport { MatchRoute } from '@tanstack/react-router'\n\nfunction Component() {\n return (\n <div>\n <MatchRoute to=\"/posts/$postId\" params={{ postId: '123' }} pending>\n {(match) => <Spinner show={!!match} wait=\"delay-50\" />}\n </MatchRoute>\n </div>\n )\n}\n```\n\n# Navigate component\n\nThe `Navigate` component is a component that can be used to navigate to a new location when rendered. This includes changes to the pathname, search params, hash, and location state. The underlying navigation will happen inside of a `useEffect` hook when successfully rendered.\n\n## Navigate props\n\nThe `Navigate` component accepts the following props:\n\n### `...options`\n\n- Type: [`NavigateOptions`](../NavigateOptionsType.md)\n\n## Navigate returns\n\n- `null`\n\n# notFound function\n\nThe `notFound` function returns a new `NotFoundError` object that can be either returned or thrown from places like a Route's `beforeLoad` or `loader` callbacks to trigger the `notFoundComponent`.\n\n## notFound options\n\nThe `notFound` function accepts a single optional argument, the `options` to create the not-found error object.\n\n- Type: [`Partial<NotFoundError>`](../NotFoundErrorType.md)\n- Optional\n\n## notFound returns\n\n- If the `throw` property is `true` in the `options` object, the `NotFoundError` object will be thrown from within the function call.\n- If the `throw` property is `false | undefined` in the `options` object, the `NotFoundError` object will be returned.\n\n## Examples\n\n```tsx\nimport { notFound, createFileRoute, rootRouteId } from '@tanstack/react-router'\n\nconst Route = new createFileRoute('/posts/$postId')({\n // throwing a not-found object\n loader: ({ context: { post } }) => {\n if (!post) {\n throw notFound()\n }\n },\n // or if you want to show a not-found on the whole page\n loader: ({ context: { team } }) => {\n if (!team) {\n throw notFound({ routeId: rootRouteId })\n }\n },\n // ... other route options\n})\n```\n\n# Outlet component\n\nThe `Outlet` component is a component that can be used to render the next child route of a parent route.\n\n## Outlet props\n\nThe `Outlet` component does not accept any props.\n\n## Outlet returns\n\n- If matched, the child route match's `component`/`errorComponent`/`pendingComponent`/`notFoundComponent`.\n- If not matched, `null`.\n\n# redirect function\n\nThe `redirect` function returns a new `Redirect` object that can be either returned or thrown from places like a Route's `beforeLoad` or `loader` callbacks to trigger _redirect_ to a new location.\n\n## redirect options\n\nThe `redirect` function accepts a single argument, the `options` to determine the redirect behavior.\n\n- Type: [`Redirect`](../RedirectType.md)\n- Required\n\n## redirect returns\n\n- If the `throw` property is `true` in the `options` object, the `Redirect` object will be thrown from within the function call.\n- If the `throw` property is `false | undefined` in the `options` object, the `Redirect` object will be returned.\n\n## Examples\n\n```tsx\nimport { redirect } from '@tanstack/react-router'\n\nconst route = createRoute({\n // throwing an internal redirect object using 'to' property\n loader: () => {\n if (!user) {\n throw redirect({\n to: '/login',\n })\n }\n },\n // throwing an external redirect object using 'href' property\n loader: () => {\n if (needsExternalAuth) {\n throw redirect({\n href: 'https://authprovider.com/login',\n })\n }\n },\n // or forcing `redirect` to throw itself\n loader: () => {\n if (!user) {\n redirect({\n to: '/login',\n throw: true,\n })\n }\n },\n // ... other route options\n})\n```\n\n# Search middleware to retain search params\n\n`retainSearchParams` is a search middleware that allows to keep search params.\n\n## retainSearchParams props\n\nThe `retainSearchParams` either accepts `true` or a list of keys of those search params that shall be retained.\nIf `true` is passed in, all search params will be retained.\n\n## Examples\n\n```tsx\nimport { z } from 'zod'\nimport { createRootRoute, retainSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst searchSchema = z.object({\n rootValue: z.string().optional(),\n})\n\nexport const Route = createRootRoute({\n validateSearch: zodValidator(searchSchema),\n search: {\n middlewares: [retainSearchParams(['rootValue'])],\n },\n})\n```\n\n```tsx\nimport { z } from 'zod'\nimport { createFileRoute, retainSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst searchSchema = z.object({\n one: z.string().optional(),\n two: z.string().optional(),\n})\n\nexport const Route = createFileRoute('/')({\n validateSearch: zodValidator(searchSchema),\n search: {\n middlewares: [retainSearchParams(true)],\n },\n})\n```\n\n# rootRouteWithContext function\n\n> [!CAUTION]\n> This function is deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createRootRouteWithContext`](../createRootRouteWithContextFunction.md) function instead.\n\nThe `rootRouteWithContext` function is a helper function that can be used to create a root route instance that requires a context type to be fulfilled when the router is created.\n\n## rootRouteWithContext generics\n\nThe `rootRouteWithContext` function accepts a single generic argument:\n\n### `TRouterContext` generic\n\n- Type: `TRouterContext`\n- Optional, **but recommended**.\n- The context type that will be required to be fulfilled when the router is created\n\n## rootRouteWithContext returns\n\n- A factory function that can be used to create a new [`createRootRoute`](../createRootRouteFunction.md) instance.\n- It accepts a single argument, the same as the [`createRootRoute`](../createRootRouteFunction.md) function.\n\n## Examples\n\n```tsx\nimport { rootRouteWithContext, createRouter } from '@tanstack/react-router'\nimport { QueryClient } from '@tanstack/react-query'\n\ninterface MyRouterContext {\n queryClient: QueryClient\n}\n\nconst rootRoute = rootRouteWithContext<MyRouterContext>()({\n component: () => <Outlet />,\n // ... root route options\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst queryClient = new QueryClient()\n\nconst router = createRouter({\n routeTree,\n context: {\n queryClient,\n },\n})\n```\n\n# Search middleware to strip search params\n\n`stripSearchParams` is a search middleware that allows to remove search params.\n\n## stripSearchParams props\n\n`stripSearchParams` accepts one of the following inputs:\n\n- `true`: if the search schema has no required params, `true` can be used to strip all search params\n- a list of keys of those search params that shall be removed; only keys of optional search params are allowed.\n- an object that conforms to the partial input search schema. The search params are compared against the values of this object; if the value is deeply equal, it will be removed. This is especially useful to strip out default search params.\n\n## Examples\n\n```tsx\nimport { z } from 'zod'\nimport { createFileRoute, stripSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst defaultValues = {\n one: 'abc',\n two: 'xyz',\n}\n\nconst searchSchema = z.object({\n one: z.string().default(defaultValues.one),\n two: z.string().default(defaultValues.two),\n})\n\nexport const Route = createFileRoute('/')({\n validateSearch: zodValidator(searchSchema),\n search: {\n // strip default values\n middlewares: [stripSearchParams(defaultValues)],\n },\n})\n```\n\n```tsx\nimport { z } from 'zod'\nimport { createRootRoute, stripSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst searchSchema = z.object({\n hello: z.string().default('world'),\n requiredParam: z.string(),\n})\n\nexport const Route = createRootRoute({\n validateSearch: zodValidator(searchSchema),\n search: {\n // always remove `hello`\n middlewares: [stripSearchParams(['hello'])],\n },\n})\n```\n\n```tsx\nimport { z } from 'zod'\nimport { createFileRoute, stripSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst searchSchema = z.object({\n one: z.string().default('abc'),\n two: z.string().default('xyz'),\n})\n\nexport const Route = createFileRoute('/')({\n validateSearch: zodValidator(searchSchema),\n search: {\n // remove all search params\n middlewares: [stripSearchParams(true)],\n },\n})\n```\n\n# useAwaited hook\n\nThe `useAwaited` method is a hook that suspends until the provided promise is resolved or rejected.\n\n## useAwaited options\n\nThe `useAwaited` hook accepts a single argument, an `options` object.\n\n### `options.promise` option\n\n- Type: `Promise<T>`\n- Required\n- The deferred promise to await.\n\n## useAwaited returns\n\n- Throws an error if the promise is rejected.\n- Suspends (throws a promise) if the promise is pending.\n- Returns the resolved value of a deferred promise if the promise is resolved.\n\n## Examples\n\n```tsx\nimport { useAwaited } from '@tanstack/react-router'\n\nfunction Component() {\n const { deferredPromise } = route.useLoaderData()\n\n const data = useAwaited({ promise: myDeferredPromise })\n // ...\n}\n```\n\n# useBlocker hook\n\nThe `useBlocker` method is a hook that [blocks navigation](../../../guide/navigation-blocking.md) when a condition is met.\n\n> \u26A0\uFE0F The following new `useBlocker` API is currently _experimental_.\n\n## useBlocker options\n\nThe `useBlocker` hook accepts a single _required_ argument, an option object:\n\n### `options.shouldBlockFn` option\n\n- Required\n- Type: `ShouldBlockFn`\n- This function should return a `boolean` or a `Promise<boolean>` that tells the blocker if it should block the current navigation\n- The function has the argument of type `ShouldBlockFnArgs` passed to it, which tells you information about the current and next route and the action performed\n- Think of this function as telling the router if it should block the navigation, so returning `true` mean that it should block the navigation and `false` meaning that it should be allowed\n\n```ts\ninterface ShouldBlockFnLocation<...> {\n routeId: TRouteId\n fullPath: TFullPath\n pathname: string\n params: TAllParams\n search: TFullSearchSchema\n}\n\ntype ShouldBlockFnArgs = {\n current: ShouldBlockFnLocation\n next: ShouldBlockFnLocation\n action: HistoryAction\n}\n```\n\n### `options.disabled` option\n\n- Optional - defaults to `false`\n- Type: `boolean`\n- Specifies if the blocker should be entirely disabled or not\n\n### `options.enableBeforeUnload` option\n\n- Optional - defaults to `true`\n- Type: `boolean | (() => boolean)`\n- Tell the blocker to sometimes or always block the browser `beforeUnload` event or not\n\n### `options.withResolver` option\n\n- Optional - defaults to `false`\n- Type: `boolean`\n- Specify if the resolver returned by the hook should be used or whether your `shouldBlockFn` function itself resolves the blocking\n\n### `options.blockerFn` option (\u26A0\uFE0F deprecated)\n\n- Optional\n- Type: `BlockerFn`\n- The function that returns a `boolean` or `Promise<boolean>` indicating whether to allow navigation.\n\n### `options.condition` option (\u26A0\uFE0F deprecated)\n\n- Optional - defaults to `true`\n- Type: `boolean`\n- A navigation attempt is blocked when this condition is `true`.\n\n## useBlocker returns\n\nAn object with the controls to allow manual blocking and unblocking of navigation.\n\n- `status` - A string literal that can be either `'blocked'` or `'idle'`\n- `next` - When status is `blocked`, a type narrrowable object that contains information about the next location\n- `current` - When status is `blocked`, a type narrrowable object that contains information about the current location\n- `action` - When status is `blocked`, a `HistoryAction` string that shows the action that triggered the navigation\n- `proceed` - When status is `blocked`, a function that allows navigation to continue\n- `reset` - When status is `blocked`, a function that cancels navigation (`status` will be reset to `'idle'`)\n\nor\n\n`void` when `withResolver` is `false`\n\n## Examples\n\nTwo common use cases for the `useBlocker` hook are:\n\n### Basic usage\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const [formIsDirty, setFormIsDirty] = useState(false)\n\n useBlocker({\n shouldBlockFn: () => formIsDirty,\n })\n\n // ...\n}\n```\n\n### Custom UI\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const [formIsDirty, setFormIsDirty] = useState(false)\n\n const { proceed, reset, status, next } = useBlocker({\n shouldBlockFn: () => formIsDirty,\n withResolver: true,\n })\n\n // ...\n\n return (\n <>\n {/* ... */}\n {status === 'blocked' && (\n <div>\n <p>You are navigating to {next.pathname}</p>\n <p>Are you sure you want to leave?</p>\n <button onClick={proceed}>Yes</button>\n <button onClick={reset}>No</button>\n </div>\n )}\n </>\n}\n```\n\n### Conditional blocking\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const { proceed, reset, status } = useBlocker({\n shouldBlockFn: ({ next }) => {\n return !next.pathname.includes('step/')\n },\n withResolver: true,\n })\n\n // ...\n\n return (\n <>\n {/* ... */}\n {status === 'blocked' && (\n <div>\n <p>Are you sure you want to leave?</p>\n <button onClick={proceed}>Yes</button>\n <button onClick={reset}>No</button>\n </div>\n )}\n </>\n )\n}\n```\n\n### Without resolver\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const [formIsDirty, setFormIsDirty] = useState(false)\n\n useBlocker({\n shouldBlockFn: ({ next }) => {\n if (next.pathname.includes('step/')) {\n return false\n }\n\n const shouldLeave = confirm('Are you sure you want to leave?')\n return !shouldLeave\n },\n })\n\n // ...\n}\n```\n\n### Type narrowing\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const [formIsDirty, setFormIsDirty] = useState(false)\n\n // block going from editor-1 to /foo/123?hello=world\n const { proceed, reset, status } = useBlocker({\n shouldBlockFn: ({ current, next }) => {\n if (\n current.routeId === '/editor-1' &&\n next.fullPath === '/foo/$id' &&\n next.params.id === '123' &&\n next.search.hello === 'world'\n ) {\n return true\n }\n return false\n },\n enableBeforeUnload: false,\n withResolver: true,\n })\n\n // ...\n}\n```\n\n# useCanGoBack hook\n\nThe `useCanGoBack` hook returns a boolean representing if the router history can safely go back without exiting the application.\n\n> \u26A0\uFE0F The following new `useCanGoBack` API is currently _experimental_.\n\n## useCanGoBack returns\n\n- If the router history is not at index `0`, `true`.\n- If the router history is at index `0`, `false`.\n\n## Limitations\n\nThe router history index is reset after a navigation with [`reloadDocument`](../NavigateOptionsType.md#reloaddocument) set as `true`. This causes the router history to consider the new location as the initial one and will cause `useCanGoBack` to return `false`.\n\n## Examples\n\n### Showing a back button\n\n```tsx\nimport { useRouter, useCanGoBack } from '@tanstack/react-router'\n\nfunction Component() {\n const router = useRouter()\n const canGoBack = useCanGoBack()\n\n return (\n <div>\n {canGoBack ? (\n <button onClick={() => router.history.back()}>Go back</button>\n ) : null}\n\n {/* ... */}\n </div>\n )\n}\n```\n\n# useChildMatches hook\n\nThe `useChildMatches` hook returns all of the child [`RouteMatch`](../RouteMatchType.md) objects from the closest match down to the leaf-most match. **It does not include the current match, which can be obtained using the `useMatch` hook.**\n\n> [!IMPORTANT]\n> If the router has pending matches and they are showing their pending component fallbacks, `router.state.pendingMatches` will used instead of `router.state.matches`.\n\n## useChildMatches options\n\nThe `useChildMatches` hook accepts a single _optional_ argument, an `options` object.\n\n### `opts.select` option\n\n- Optional\n- `(matches: RouteMatch[]) => TSelected`\n- If supplied, this function will be called with the route matches and the return value will be returned from `useChildMatches`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useChildMatches returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, an array of [`RouteMatch`](../RouteMatchType.md) objects.\n\n## Examples\n\n```tsx\nimport { useChildMatches } from '@tanstack/react-router'\n\nfunction Component() {\n const childMatches = useChildMatches()\n // ...\n}\n```\n\n# useLinkProps hook\n\nThe `useLinkProps` hook that takes an object as its argument and returns a `React.AnchorHTMLAttributes<HTMLAnchorElement>` props object. These props can then be safely applied to an anchor element to create a link that can be used to navigate to the new location. This includes changes to the pathname, search params, hash, and location state.\n\n## useLinkProps options\n\n```tsx\ntype UseLinkPropsOptions = ActiveLinkOptions &\n React.AnchorHTMLAttributes<HTMLAnchorElement>\n```\n\n- [`ActiveLinkOptions`](../ActiveLinkOptionsType.md)\n- The `useLinkProps` options are used to build a [`LinkProps`](../LinkPropsType.md) object.\n- It also extends the `React.AnchorHTMLAttributes<HTMLAnchorElement>` type, so that any additional props that are passed to the `useLinkProps` hook will be merged with the [`LinkProps`](../LinkPropsType.md) object.\n\n## useLinkProps returns\n\n- A `React.AnchorHTMLAttributes<HTMLAnchorElement>` object that can be applied to an anchor element to create a link that can be used to navigate to the new location\n\n# useLoaderData hook\n\nThe `useLoaderData` hook returns the loader data from the closest [`RouteMatch`](../RouteMatchType.md) in the component tree.\n\n## useLoaderData options\n\nThe `useLoaderData` hook accepts an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- The route id of the closest parent match\n- Optional, but recommended for full type safety.\n- If `opts.strict` is `true`, TypeScript will warn for this option if it is not provided.\n- If `opts.strict` is `false`, TypeScript will provided loosened types for the returned loader data.\n\n### `opts.strict` option\n\n- Type: `boolean`\n- Optional - `default: true`\n- If `false`, the `opts.from` option will be ignored and types will be loosened to to reflect the shared types of all possible loader data.\n\n### `opts.select` option\n\n- Optional\n- `(loaderData: TLoaderData) => TSelected`\n- If supplied, this function will be called with the loader data and the return value will be returned from `useLoaderData`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useLoaderData returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, the loader data or a loosened version of the loader data if `opts.strict` is `false`.\n\n## Examples\n\n```tsx\nimport { useLoaderData } from '@tanstack/react-router'\n\nfunction Component() {\n const loaderData = useLoaderData({ from: '/posts/$postId' })\n // ^? { postId: string, body: string, ... }\n // ...\n}\n```\n\n# useLoaderDeps hook\n\nThe `useLoaderDeps` hook is a hook that returns an object with the dependencies that are used to trigger the `loader` for a given route.\n\n## useLoaderDepsHook options\n\nThe `useLoaderDepsHook` hook accepts an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- Required\n- The RouteID or path to get the loader dependencies from.\n\n### `opts.select` option\n\n- Type: `(deps: TLoaderDeps) => TSelected`\n- Optional\n- If supplied, this function will be called with the loader dependencies object and the return value will be returned from `useLoaderDeps`.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useLoaderDeps returns\n\n- An object of the loader dependencies or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useLoaderDeps } from '@tanstack/react-router'\n\nconst routeApi = getRouteApi('/posts/$postId')\n\nfunction Component() {\n const deps = useLoaderDeps({ from: '/posts/$postId' })\n\n // OR\n\n const routeDeps = routeApi.useLoaderDeps()\n\n // OR\n\n const postId = useLoaderDeps({\n from: '/posts',\n select: (deps) => deps.view,\n })\n\n // ...\n}\n```\n\n# useLocation hook\n\nThe `useLocation` method is a hook that returns the current [`location`](../ParsedLocationType.md) object. This hook is useful for when you want to perform some side effect whenever the current location changes.\n\n## useLocation options\n\nThe `useLocation` hook accepts an optional `options` object.\n\n### `opts.select` option\n\n- Type: `(state: ParsedLocationType) => TSelected`\n- Optional\n- If supplied, this function will be called with the [`location`](../ParsedLocationType.md) object and the return value will be returned from `useLocation`.\n\n## useLocation returns\n\n- The current [`location`](../ParsedLocationType.md) object or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useLocation } from '@tanstack/react-router'\n\nfunction Component() {\n const location = useLocation()\n // ^ ParsedLocation\n\n // OR\n\n const pathname = useLocation({\n select: (location) => location.pathname,\n })\n // ^ string\n\n // ...\n}\n```\n\n# useMatch hook\n\nThe `useMatch` hook returns a [`RouteMatch`](../RouteMatchType.md) in the component tree. The raw route match contains all of the information about a route match in the router and also powers many other hooks under the hood like `useParams`, `useLoaderData`, `useRouteContext`, and `useSearch`.\n\n## useMatch options\n\nThe `useMatch` hook accepts a single argument, an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- The route id of a match\n- Optional, but recommended for full type safety.\n- If `opts.strict` is `true`, `from` is required and TypeScript will warn for this option if it is not provided.\n- If `opts.strict` is `false`, `from` must not be set and TypeScript will provided loosened types for the returned [`RouteMatch`](../RouteMatchType.md).\n\n### `opts.strict` option\n\n- Type: `boolean`\n- Optional\n- `default: true`\n- If `false`, the `opts.from` must not be set and types will be loosened to `Partial<RouteMatch>` to reflect the shared types of all matches.\n\n### `opts.select` option\n\n- Optional\n- `(match: RouteMatch) => TSelected`\n- If supplied, this function will be called with the route match and the return value will be returned from `useMatch`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n### `opts.shouldThrow` option\n\n- Type: `boolean`\n- Optional\n- `default: true`\n- If `false`,`useMatch` will not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will return `undefined`.\n\n## useMatch returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, the [`RouteMatch`](../RouteMatchType.md) object or a loosened version of the `RouteMatch` object if `opts.strict` is `false`.\n\n## Examples\n\n### Accessing a route match\n\n```tsx\nimport { useMatch } from '@tanstack/react-router'\n\nfunction Component() {\n const match = useMatch({ from: '/posts/$postId' })\n // ^? strict match for RouteMatch\n // ...\n}\n```\n\n### Accessing the root route's match\n\n```tsx\nimport {\n useMatch,\n rootRouteId, // <<<< use this token!\n} from '@tanstack/react-router'\n\nfunction Component() {\n const match = useMatch({ from: rootRouteId })\n // ^? strict match for RouteMatch\n // ...\n}\n```\n\n### Checking if a specific route is currently rendered\n\n```tsx\nimport { useMatch } from '@tanstack/react-router'\n\nfunction Component() {\n const match = useMatch({ from: '/posts', shouldThrow: false })\n // ^? RouteMatch | undefined\n if (match !== undefined) {\n // ...\n }\n}\n```\n\n# useMatchRoute hook\n\nThe `useMatchRoute` hook is a hook that returns a `matchRoute` function that can be used to match a route against either the current or pending location.\n\n## useMatchRoute returns\n\n- A `matchRoute` function that can be used to match a route against either the current or pending location.\n\n## matchRoute function\n\nThe `matchRoute` function is a function that can be used to match a route against either the current or pending location.\n\n### matchRoute function options\n\nThe `matchRoute` function accepts a single argument, an `options` object.\n\n- Type: [`UseMatchRouteOptions`](../UseMatchRouteOptionsType.md)\n\n### matchRoute function returns\n\n- The matched route's params or `false` if no route was matched\n\n## Examples\n\n```tsx\nimport { useMatchRoute } from '@tanstack/react-router'\n\n// Current location: /posts/123\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts/$postId' })\n // ^ { postId: '123' }\n}\n\n// Current location: /posts/123\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts' })\n // ^ false\n}\n\n// Current location: /posts/123\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts', fuzzy: true })\n // ^ {}\n}\n\n// Current location: /posts\n// Pending location: /posts/123\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts/$postId', pending: true })\n // ^ { postId: '123' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts/$postId/foo/$fooId' })\n // ^ { postId: '123', fooId: '456' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { postId: '123' },\n })\n // ^ { postId: '123', fooId: '456' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { postId: '789' },\n })\n // ^ false\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { fooId: '456' },\n })\n // ^ { postId: '123', fooId: '456' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { postId: '123', fooId: '456' },\n })\n // ^ { postId: '123', fooId: '456' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { postId: '789', fooId: '456' },\n })\n // ^ false\n}\n```\n\n# useMatches hook\n\nThe `useMatches` hook returns all of the [`RouteMatch`](../RouteMatchType.md) objects from the router **regardless of its callers position in the React component tree**.\n\n> [!TIP]\n> If you only want the parent or child matches, then you can use the [`useParentMatches`](../useParentMatchesHook.md) or the [`useChildMatches`](../useChildMatchesHook.md) based on the selection you need.\n\n## useMatches options\n\nThe `useMatches` hook accepts a single _optional_ argument, an `options` object.\n\n### `opts.select` option\n\n- Optional\n- `(matches: RouteMatch[]) => TSelected`\n- If supplied, this function will be called with the route matches and the return value will be returned from `useMatches`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useMatches returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, an array of [`RouteMatch`](../RouteMatchType.md) objects.\n\n## Examples\n\n```tsx\nimport { useMatches } from '@tanstack/react-router'\n\nfunction Component() {\n const matches = useMatches()\n // ^? [RouteMatch, RouteMatch, ...]\n // ...\n}\n```\n\n# useNavigate hook\n\nThe `useNavigate` hook is a hook that returns a `navigate` function that can be used to navigate to a new location. This includes changes to the pathname, search params, hash, and location state.\n\n## useNavigate options\n\nThe `useNavigate` hook accepts a single argument, an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- Optional\n- Description: The location to navigate from. This is useful when you want to navigate to a new location from a specific location, rather than the current location.\n\n## useNavigate returns\n\n- A `navigate` function that can be used to navigate to a new location.\n\n## navigate function\n\nThe `navigate` function is a function that can be used to navigate to a new location.\n\n### navigate function options\n\nThe `navigate` function accepts a single argument, an `options` object.\n\n- Type: [`NavigateOptions`](../NavigateOptionsType.md)\n\n### navigate function returns\n\n- A `Promise` that resolves when the navigation is complete\n\n## Examples\n\n```tsx\nimport { useNavigate } from '@tanstack/react-router'\n\nfunction PostsPage() {\n const navigate = useNavigate({ from: '/posts' })\n const handleClick = () => navigate({ search: { page: 2 } })\n // ...\n}\n\nfunction Component() {\n const navigate = useNavigate()\n return (\n <div>\n <button\n onClick={() =>\n navigate({\n to: '/posts',\n })\n }\n >\n Posts\n </button>\n <button\n onClick={() =>\n navigate({\n to: '/posts',\n search: { page: 2 },\n })\n }\n >\n Posts (Page 2)\n </button>\n <button\n onClick={() =>\n navigate({\n to: '/posts',\n hash: 'my-hash',\n })\n }\n >\n Posts (Hash)\n </button>\n <button\n onClick={() =>\n navigate({\n to: '/posts',\n state: { from: 'home' },\n })\n }\n >\n Posts (State)\n </button>\n </div>\n )\n}\n```\n\n# useParams hook\n\nThe `useParams` method returns all of the path parameters that were parsed for the closest match and all of its parent matches.\n\n## useParams options\n\nThe `useParams` hook accepts an optional `options` object.\n\n### `opts.strict` option\n\n- Type: `boolean`\n- Optional - `default: true`\n- If `false`, the `opts.from` option will be ignored and types will be loosened to `Partial<AllParams>` to reflect the shared types of all params.\n\n### `opts.shouldThrow` option\n\n- Type: `boolean`\n- Optional\n- `default: true`\n- If `false`,`useParams` will not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will return `undefined`.\n\n### `opts.select` option\n\n- Optional\n- `(params: AllParams) => TSelected`\n- If supplied, this function will be called with the params object and the return value will be returned from `useParams`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useParams returns\n\n- An object of of the match's and parent match path params or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useParams } from '@tanstack/react-router'\n\nconst routeApi = getRouteApi('/posts/$postId')\n\nfunction Component() {\n const params = useParams({ from: '/posts/$postId' })\n\n // OR\n\n const routeParams = routeApi.useParams()\n\n // OR\n\n const postId = useParams({\n from: '/posts/$postId',\n select: (params) => params.postId,\n })\n\n // OR\n\n const looseParams = useParams({ strict: false })\n\n // ...\n}\n```\n\n# useParentMatches hook\n\nThe `useParentMatches` hook returns all of the parent [`RouteMatch`](../RouteMatchType.md) objects from the root down to the immediate parent of the current match in context. **It does not include the current match, which can be obtained using the `useMatch` hook.**\n\n> [!IMPORTANT]\n> If the router has pending matches and they are showing their pending component fallbacks, `router.state.pendingMatches` will used instead of `router.state.matches`.\n\n## useParentMatches options\n\nThe `useParentMatches` hook accepts an optional `options` object.\n\n### `opts.select` option\n\n- Optional\n- `(matches: RouteMatch[]) => TSelected`\n- If supplied, this function will be called with the route matches and the return value will be returned from `useParentMatches`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useParentMatches returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, an array of [`RouteMatch`](../RouteMatchType.md) objects.\n\n## Examples\n\n```tsx\nimport { useParentMatches } from '@tanstack/react-router'\n\nfunction Component() {\n const parentMatches = useParentMatches()\n // ^ [RouteMatch, RouteMatch, ...]\n}\n```\n\n# useRouteContext hook\n\nThe `useRouteContext` method is a hook that returns the current context for the current route. This hook is useful for accessing the current route context in a component.\n\n## useRouteContext options\n\nThe `useRouteContext` hook accepts an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- Required\n- The RouteID to match the route context from.\n\n### `opts.select` option\n\n- Type: `(context: RouteContext) => TSelected`\n- Optional\n- If supplied, this function will be called with the route context object and the return value will be returned from `useRouteContext`.\n\n## useRouteContext returns\n\n- The current context for the current route or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useRouteContext } from '@tanstack/react-router'\n\nfunction Component() {\n const context = useRouteContext({ from: '/posts/$postId' })\n // ^ RouteContext\n\n // OR\n\n const selected = useRouteContext({\n from: '/posts/$postId',\n select: (context) => context.postId,\n })\n // ^ string\n\n // ...\n}\n```\n\n# useRouter hook\n\nThe `useRouter` method is a hook that returns the current instance of [`Router`](../RouterType.md) from context. This hook is useful for accessing the router instance in a component.\n\n## useRouter returns\n\n- The current [`Router`](../RouterType.md) instance.\n\n> \u26A0\uFE0F\u26A0\uFE0F\u26A0\uFE0F **`router.state` is always up to date, but NOT REACTIVE. If you use `router.state` in a component, the component will not re-render when the router state changes. To get a reactive version of the router state, use the [`useRouterState`](../useRouterStateHook.md) hook.**\n\n## Examples\n\n```tsx\nimport { useRouter } from '@tanstack/react-router'\n\nfunction Component() {\n const router = useRouter()\n // ^ Router\n\n // ...\n}\n```\n\n# useRouterState hook\n\nThe `useRouterState` method is a hook that returns the current internal state of the router. This hook is useful for accessing the current state of the router in a component.\n\n> [!TIP]\n> If you want to access the current location or the current matches, you should try out the [`useLocation`](../useLocationHook.md) and [`useMatches`](../useMatchesHook.md) hooks first. These hooks are designed to be more ergonomic and easier to use than accessing the router state directly.\n\n## useRouterState options\n\nThe `useRouterState` hook accepts an optional `options` object.\n\n### `opts.select` option\n\n- Type: `(state: RouterState) => TSelected`\n- Optional\n- If supplied, this function will be called with the [`RouterState`](../RouterStateType.md) object and the return value will be returned from `useRouterState`.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useRouterState returns\n\n- The current [`RouterState`](../RouterStateType.md) object or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useRouterState } from '@tanstack/react-router'\n\nfunction Component() {\n const state = useRouterState()\n // ^ RouterState\n\n // OR\n\n const selected = useRouterState({\n select: (state) => state.location,\n })\n // ^ ParsedLocation\n\n // ...\n}\n```\n\n# useSearch hook\n\nThe `useSearch` method is a hook that returns the current search query parameters as an object for the current location. This hook is useful for accessing the current search string and query parameters in a component.\n\n## useSearch options\n\nThe `useSearch` hook accepts an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- Required\n- The RouteID to match the search query parameters from.\n\n### `opts.shouldThrow` option\n\n- Type: `boolean`\n- Optional\n- `default: true`\n- If `false`,`useSearch` will not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will return `undefined`.\n\n### `opts.select` option\n\n- Type: `(search: SelectedSearchSchema) => TSelected`\n- Optional\n- If supplied, this function will be called with the search object and the return value will be returned from `useSearch`.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n### `opts.strict` option\n\n- Type: `boolean`\n- Optional - `default: true`\n- If `false`, the `opts.from` option will be ignored and types will be loosened to `Partial<FullSearchSchema>` to reflect the shared types of all search query parameters.\n\n## useSearch returns\n\n- If `opts.from` is provided, an object of the search query parameters for the current location or `TSelected` if a `select` function is provided.\n- If `opts.strict` is `false`, an object of the search query parameters for the current location or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useSearch } from '@tanstack/react-router'\n\nfunction Component() {\n const search = useSearch({ from: '/posts/$postId' })\n // ^ FullSearchSchema\n\n // OR\n\n const selected = useSearch({\n from: '/posts/$postId',\n select: (search) => search.postView,\n })\n // ^ string\n\n // OR\n\n const looseSearch = useSearch({ strict: false })\n // ^ Partial<FullSearchSchema>\n\n // ...\n}\n```\n\n";
|
|
1
|
+
declare const _default: "# ActiveLinkOptions type\n\nThe `ActiveLinkOptions` type extends the [`LinkOptions`](../LinkOptionsType.md) type and contains additional options that can be used to describe how a link should be styled when it is active.\n\n```tsx\ntype ActiveLinkOptions = LinkOptions & {\n activeProps?:\n | React.AnchorHTMLAttributes<HTMLAnchorElement>\n | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)\n inactiveProps?:\n | React.AnchorHTMLAttributes<HTMLAnchorElement>\n | (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)\n}\n```\n\n## ActiveLinkOptions properties\n\nThe `ActiveLinkOptions` object accepts/contains the following properties:\n\n### `activeProps`\n\n- `React.AnchorHTMLAttributes<HTMLAnchorElement>`\n- Optional\n- The props that will be applied to the anchor element when the link is active\n\n### `inactiveProps`\n\n- Type: `React.AnchorHTMLAttributes<HTMLAnchorElement>`\n- Optional\n- The props that will be applied to the anchor element when the link is inactive\n\n# AsyncRouteComponent type\n\nThe `AsyncRouteComponent` type is used to describe a code-split route component that can be preloaded using a `component.preload()` method.\n\n```tsx\ntype AsyncRouteComponent<TProps> = SyncRouteComponent<TProps> & {\n preload?: () => Promise<void>\n}\n```\n\n# FileRoute class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createFileRoute`](../createFileRouteFunction.md) function instead.\n\nThe `FileRoute` class is a factory that can be used to create a file-based route instance. This route instance can then be used to automatically generate a route tree with the `tsr generate` and `tsr watch` commands.\n\n## `FileRoute` constructor\n\nThe `FileRoute` constructor accepts a single argument: the `path` of the file that the route will be generated for.\n\n### Constructor options\n\n- Type: `string` literal\n- Required, but **automatically inserted and updated by the `tsr generate` and `tsr watch` commands**.\n- The full path of the file that the route will be generated from.\n\n### Constructor returns\n\n- An instance of the `FileRoute` class that can be used to create a route.\n\n## `FileRoute` methods\n\nThe `FileRoute` class implements the following method(s):\n\n### `.createRoute` method\n\nThe `createRoute` method is a method that can be used to configure the file route instance. It accepts a single argument: the `options` that will be used to configure the file route instance.\n\n#### .createRoute options\n\n- Type: `Omit<RouteOptions, 'getParentRoute' | 'path' | 'id'>`\n- [`RouteOptions`](../RouteOptionsType.md)\n- Optional\n- The same options that are available to the `Route` class, but with the `getParentRoute`, `path`, and `id` options omitted since they are unnecessary for file-based routing.\n\n#### .createRoute returns\n\nA [`Route`](../RouteType.md) instance that can be used to configure the route to be inserted into the route-tree.\n\n> \u26A0\uFE0F Note: For `tsr generate` and `tsr watch` to work properly, the file route instance must be exported from the file using the `Route` identifier.\n\n### Examples\n\n```tsx\nimport { FileRoute } from '@tanstack/react-router'\n\nexport const Route = new FileRoute('/').createRoute({\n loader: () => {\n return 'Hello World'\n },\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# LinkOptions type\n\nThe `LinkOptions` type extends the [`NavigateOptions`](../NavigateOptionsType.md) type and contains additional options that can be used by TanStack Router when handling actual anchor element attributes.\n\n```tsx\ntype LinkOptions = NavigateOptions & {\n target?: HTMLAnchorElement['target']\n activeOptions?: ActiveOptions\n preload?: false | 'intent'\n preloadDelay?: number\n disabled?: boolean\n}\n```\n\n## LinkOptions properties\n\nThe `LinkOptions` object accepts/contains the following properties:\n\n### `target`\n\n- Type: `HTMLAnchorElement['target']`\n- Optional\n- The standard anchor tag target attribute\n\n### `activeOptions`\n\n- Type: `ActiveOptions`\n- Optional\n- The options that will be used to determine if the link is active\n\n### `preload`\n\n- Type: `false | 'intent' | 'viewport' | 'render'`\n- Optional\n- If set, the link's preloading strategy will be set to this value.\n- See the [Preloading guide](../../../guide/preloading.md) for more information.\n\n### `preloadDelay`\n\n- Type: `number`\n- Optional\n- Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled.\n\n### `disabled`\n\n- Type: `boolean`\n- Optional\n- If true, will render the link without the href attribute\n\n# LinkProps type\n\nThe `LinkProps` type extends the [`ActiveLinkOptions`](../ActiveLinkOptionsType.md) and `React.AnchorHTMLAttributes<HTMLAnchorElement>` types and contains additional props specific to the `Link` component.\n\n```tsx\ntype LinkProps = ActiveLinkOptions &\n Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'children'> & {\n children?:\n | React.ReactNode\n | ((state: { isActive: boolean }) => React.ReactNode)\n }\n```\n\n## LinkProps properties\n\n- All of the props from [`ActiveLinkOptions`](../ActiveLinkOptionsType.md)\n- All of the props from `React.AnchorHTMLAttributes<HTMLAnchorElement>`\n\n#### `children`\n\n- Type: `React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode)`\n- Optional\n- The children that will be rendered inside of the anchor element. If a function is provided, it will be called with an object that contains the `isActive` boolean value that can be used to determine if the link is active.\n\n# MatchRouteOptions type\n\nThe `MatchRouteOptions` type is used to describe the options that can be used when matching a route.\n\n```tsx\ninterface MatchRouteOptions {\n pending?: boolean\n caseSensitive?: boolean\n includeSearch?: boolean\n fuzzy?: boolean\n}\n```\n\n## MatchRouteOptions properties\n\nThe `MatchRouteOptions` type has the following properties:\n\n### `pending` property\n\n- Type: `boolean`\n- Optional\n- If `true`, will match against pending location instead of the current location\n\n### `caseSensitive` property\n\n- Type: `boolean`\n- Optional\n- If `true`, will match against the current location with case sensitivity\n\n### `includeSearch` property\n\n- Type: `boolean`\n- Optional\n- If `true`, will match against the current location's search params using a deep inclusive check. e.g. `{ a: 1 }` will match for a current location of `{ a: 1, b: 2 }`\n\n### `fuzzy` property\n\n- Type: `boolean`\n- Optional\n- If `true`, will match against the current location using a fuzzy match. e.g. `/posts` will match for a current location of `/posts/123`\n\n# NavigateOptions type\n\nThe `NavigateOptions` type is used to describe the options that can be used when describing a navigation action in TanStack Router.\n\n```tsx\ntype NavigateOptions = ToOptions & {\n replace?: boolean\n resetScroll?: boolean\n hashScrollIntoView?: boolean | ScrollIntoViewOptions\n viewTransition?: boolean | ViewTransitionOptions\n ignoreBlocker?: boolean\n reloadDocument?: boolean\n href?: string\n}\n```\n\n## NavigateOptions properties\n\nThe `NavigateOptions` object accepts the following properties:\n\n### `replace`\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`.\n- If `true`, the location will be committed to the browser history using `history.replace` instead of `history.push`.\n\n### `resetScroll`\n\n- Type: `boolean`\n- Optional\n- Defaults to `true` so that the scroll position will be reset to 0,0 after the location is committed to the browser history.\n- If `false`, the scroll position will not be reset to 0,0 after the location is committed to history.\n\n### `hashScrollIntoView`\n\n- Type: `boolean | ScrollIntoViewOptions`\n- Optional\n- Defaults to `true` so the element with an id matching the hash will be scrolled into view after the location is committed to history.\n- If `false`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.\n- If an object is provided, it will be passed to the `scrollIntoView` method as options.\n- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on `ScrollIntoViewOptions`.\n\n### `viewTransition`\n\n- Type: `boolean | ViewTransitionOptions`\n- Optional\n- Defaults to `false`.\n- If `true`, navigation will be called using `document.startViewTransition()`.\n- If [`ViewTransitionOptions`](../ViewTransitionOptionsType.md), route navigations will be called using `document.startViewTransition({update, types})` where `types` will determine the strings array passed with `ViewTransitionOptions[\"types\"]`. If the browser does not support viewTransition types, the navigation will fall back to normal `document.startTransition()`, same as if `true` was passed.\n- If the browser does not support this api, this option will be ignored.\n- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.\n- See [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types) for more information on viewTransition types\n\n### `ignoreBlocker`\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`.\n- If `true`, navigation will ignore any blockers that might prevent it.\n\n### `reloadDocument`\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`.\n- If `true`, navigation to a route inside of router will trigger a full page load instead of the traditional SPA navigation.\n\n### `href`\n\n- Type: `string`\n- Optional\n- This can be used instead of `to` to navigate to a fully built href, e.g. pointing to an external target.\n\n- [`ToOptions`](../ToOptionsType.md)\n\n# NotFoundError\n\nThe `NotFoundError` type is used to represent a not-found error in TanStack Router.\n\n```tsx\nexport type NotFoundError = {\n global?: boolean\n data?: any\n throw?: boolean\n routeId?: string\n headers?: HeadersInit\n}\n```\n\n## NotFoundError properties\n\nThe `NotFoundError` object accepts/contains the following properties:\n\n### `global` property (\u26A0\uFE0F deprecated, use `routeId: rootRouteId` instead)\n\n- Type: `boolean`\n- Optional - `default: false`\n- If true, the not-found error will be handled by the `notFoundComponent` of the root route instead of bubbling up from the route that threw it. This has the same behavior as importing the root route and calling `RootRoute.notFound()`.\n\n### `data` property\n\n- Type: `any`\n- Optional\n- Custom data that is passed into to `notFoundComponent` when the not-found error is handled\n\n### `throw` property\n\n- Type: `boolean`\n- Optional - `default: false`\n- If provided, will throw the not-found object instead of returning it. This can be useful in places where `throwing` in a function might cause it to have a return type of `never`. In that case, you can use `notFound({ throw: true })` to throw the not-found object instead of returning it.\n\n### `route` property\n\n- Type: `string`\n- Optional\n- The ID of the route that will attempt to handle the not-found error. If the route does not have a `notFoundComponent`, the error will bubble up to the parent route (and be handled by the root route if necessary). By default, TanStack Router will attempt to handle the not-found error with the route that threw it.\n\n### `headers` property\n\n- Type: `HeadersInit`\n- Optional\n- HTTP headers to be included when the not-found error is handled on the server side.\n\n# NotFoundRoute class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the `notFoundComponent` route option that is present during route configuration.\n> See the [Not Found Errors guide](../../../guide/not-found-errors.md) for more information.\n\nThe `NotFoundRoute` class extends the `Route` class and can be used to create a not found route instance. A not found route instance can be passed to the `routerOptions.notFoundRoute` option to configure a default not-found/404 route for every branch of the route tree.\n\n## Constructor options\n\nThe `NotFoundRoute` constructor accepts an object as its only argument.\n\n- Type:\n\n```tsx\nOmit<\n RouteOptions,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n>\n```\n\n- [RouteOptions](../RouteOptionsType.md)\n- Required\n- The options that will be used to configure the not found route instance.\n\n## Examples\n\n```tsx\nimport { NotFoundRoute, createRouter } from '@tanstack/react-router'\nimport { Route as rootRoute } from './routes/__root'\nimport { routeTree } from './routeTree.gen'\n\nconst notFoundRoute = new NotFoundRoute({\n getParentRoute: () => rootRoute,\n component: () => <div>Not found!!!</div>,\n})\n\nconst router = createRouter({\n routeTree,\n notFoundRoute,\n})\n\n// ... other code\n```\n\n# ParsedHistoryState type\n\nThe `ParsedHistoryState` type represents a parsed state object. Additionally to `HistoryState`, it contains the index and the unique key of the route.\n\n```tsx\nexport type ParsedHistoryState = HistoryState & {\n key?: string // TODO: Remove in v2 - use __TSR_key instead\n __TSR_key?: string\n __TSR_index: number\n}\n```\n\n# ParsedLocation type\n\nThe `ParsedLocation` type represents a parsed location in TanStack Router. It contains a lot of useful information about the current location, including the pathname, search params, hash, location state, and route masking information.\n\n```tsx\ninterface ParsedLocation {\n href: string\n pathname: string\n search: TFullSearchSchema\n searchStr: string\n state: ParsedHistoryState\n hash: string\n maskedLocation?: ParsedLocation\n unmaskOnReload?: boolean\n}\n```\n\n# Redirect type\n\nThe `Redirect` type is used to represent a redirect action in TanStack Router.\n\n```tsx\nexport type Redirect = {\n statusCode?: number\n throw?: any\n headers?: HeadersInit\n} & NavigateOptions\n```\n\n- [`NavigateOptions`](../NavigateOptionsType.md)\n\n## Redirect properties\n\nThe `Redirect` object accepts/contains the following properties:\n\n### `statusCode` property\n\n- Type: `number`\n- Optional\n- The HTTP status code to use when redirecting\n\n### `throw` property\n\n- Type: `any`\n- Optional\n- If provided, will throw the redirect object instead of returning it. This can be useful in places where `throwing` in a function might cause it to have a return type of `never`. In that case, you can use `redirect({ throw: true })` to throw the redirect object instead of returning it.\n\n### `headers` property\n\n- Type: `HeadersInit`\n- Optional\n- The HTTP headers to use when redirecting.\n\n### Navigation Properties\n\nSince `Redirect` extends `NavigateOptions`, it also supports navigation properties:\n\n- **`to`**: Use for internal application routes (e.g., `/dashboard`, `../profile`)\n- **`href`**: Use for external URLs (e.g., `https://example.com`, `https://authprovider.com`)\n\n> **Important**: For external URLs, always use the `href` property instead of `to`. The `to` property is designed for internal navigation within your application.\n\n# Register type\n\nThis type is used to register a route tree with a router instance. Doing so unlocks the full type safety of TanStack Router, including top-level exports from the `@tanstack/react-router` package.\n\n```tsx\nexport type Register = {\n // router: [Your router type here]\n}\n```\n\nTo register a route tree with a router instance, use declaration merging to add the type of your router instance to the Register interface under the `router` property:\n\n## Examples\n\n```tsx\nconst router = createRouter({\n // ...\n})\n\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n```\n\n# RootRoute class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createRootRoute`](../createRootRouteFunction.md) function instead.\n\nThe `RootRoute` class extends the `Route` class and can be used to create a root route instance. A root route instance can then be used to create a route tree.\n\n## `RootRoute` constructor\n\nThe `RootRoute` constructor accepts an object as its only argument.\n\n### Constructor options\n\nThe options that will be used to configure the root route instance.\n\n- Type:\n\n```tsx\nOmit<\n RouteOptions,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n>\n```\n\n- [`RouteOptions`](../RouteOptionsType.md)\n- Optional\n\n## Constructor returns\n\nA new [`Route`](../RouteType.md) instance.\n\n## Examples\n\n```tsx\nimport { RootRoute, createRouter, Outlet } from '@tanstack/react-router'\n\nconst rootRoute = new RootRoute({\n component: () => <Outlet />,\n // ... root route options\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst router = createRouter({\n routeTree,\n})\n```\n\n# RouteApi class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`getRouteApi`](../getRouteApiFunction.md) function instead.\n\nThe `RouteApi` class provides type-safe version of common hooks like `useParams`, `useSearch`, `useRouteContext`, `useNavigate`, `useLoaderData`, and `useLoaderDeps` that are pre-bound to a specific route ID and corresponding registered route types.\n\n## Constructor options\n\nThe `RouteApi` constructor accepts a single argument: the `options` that will be used to configure the `RouteApi` instance.\n\n### `opts.routeId` option\n\n- Type: `string`\n- Required\n- The route ID to which the `RouteApi` instance will be bound\n\n## Constructor returns\n\n- An instance of the [`RouteApi`](../RouteApiType.md) that is pre-bound to the route ID that it was called with.\n\n## Examples\n\n```tsx\nimport { RouteApi } from '@tanstack/react-router'\n\nconst routeApi = new RouteApi({ id: '/posts' })\n\nexport function PostsPage() {\n const posts = routeApi.useLoaderData()\n // ...\n}\n```\n\n# RouteApi Type\n\nThe `RouteApi` describes an instance that provides type-safe versions of common hooks like `useParams`, `useSearch`, `useRouteContext`, `useNavigate`, `useLoaderData`, and `useLoaderDeps` that are pre-bound to a specific route ID and corresponding registered route types.\n\n## `RouteApi` properties and methods\n\nThe `RouteApi` has the following properties and methods:\n\n### `useMatch` method\n\n```tsx\n useMatch<TSelected = TAllContext>(opts?: {\n select?: (match: TAllContext) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useMatch`](../useMatchHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: RouteMatch) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useMatch`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `RouteMatch` object or a loosened version of the `RouteMatch` object if `opts.strict` is `false`.\n\n### `useRouteContext` method\n\n```tsx\n useRouteContext<TSelected = TAllContext>(opts?: {\n select?: (search: TAllContext) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useRouteContext`](../useRouteContextHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: RouteContext) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useRouteContext`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `RouteContext` object or a loosened version of the `RouteContext` object if `opts.strict` is `false`.\n\n### `useSearch` method\n\n```tsx\n useSearch<TSelected = TFullSearchSchema>(opts?: {\n select?: (search: TFullSearchSchema) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useSearch`](../useSearchHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: TFullSearchSchema) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useSearch`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `TFullSearchSchema` object or a loosened version of the `TFullSearchSchema` object if `opts.strict` is `false`.\n\n### `useParams` method\n\n```tsx\n useParams<TSelected = TAllParams>(opts?: {\n select?: (params: TAllParams) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useParams`](../useParamsHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: TAllParams) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useParams`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `TAllParams` object or a loosened version of the `TAllParams` object if `opts.strict` is `false`.\n\n### `useLoaderData` method\n\n```tsx\n useLoaderData<TSelected = TLoaderData>(opts?: {\n select?: (search: TLoaderData) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useLoaderData`](../useLoaderDataHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: TLoaderData) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useLoaderData`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `TLoaderData` object or a loosened version of the `TLoaderData` object if `opts.strict` is `false`.\n\n### `useLoaderDeps` method\n\n```tsx\n useLoaderDeps<TSelected = TLoaderDeps>(opts?: {\n select?: (search: TLoaderDeps) => TSelected\n }): TSelected\n```\n\n- A type-safe version of the [`useLoaderDeps`](../useLoaderDepsHook.md) hook that is pre-bound to the route ID that the `RouteApi` instance was created with.\n- Options\n - `opts.select`\n - Optional\n - `(match: TLoaderDeps) => TSelected`\n - If supplied, this function will be called with the route match and the return value will be returned from `useLoaderDeps`.\n - `opts.structuralSharing`\n - Optional\n - `boolean`\n - Configures whether structural sharing is enabled for the value returned by `select`.\n - See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n- Returns\n - If a `select` function is provided, the return value of the `select` function.\n - If no `select` function is provided, the `TLoaderDeps` object.\n\n### `useNavigate` method\n\n```tsx\n useNavigate(): // navigate function\n```\n\n- A type-safe version of [`useNavigate`](../useNavigateHook.md) that is pre-bound to the route ID that the `RouteApi` instance was created with.\n\n# Route class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createRoute`](../createRouteFunction.md) function instead.\n\nThe `Route` class implements the `RouteApi` class and can be used to create route instances. A route instance can then be used to create a route tree.\n\n## `Route` constructor\n\nThe `Route` constructor accepts an object as its only argument.\n\n### Constructor options\n\n- Type: [`RouteOptions`](../RouteOptionsType.md)\n- Required\n- The options that will be used to configure the route instance\n\n### Constructor returns\n\nA new [`Route`](../RouteType.md) instance.\n\n## Examples\n\n```tsx\nimport { Route } from '@tanstack/react-router'\nimport { rootRoute } from './__root'\n\nconst indexRoute = new Route({\n getParentRoute: () => rootRoute,\n path: '/',\n loader: () => {\n return 'Hello World'\n },\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = indexRoute.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# RouteMask type\n\nThe `RouteMask` type extends the [`ToOptions`](../ToOptionsType.md) type and has other the necessary properties to create a route mask.\n\n## RouteMask properties\n\nThe `RouteMask` type accepts an object with the following properties:\n\n### `...ToOptions`\n\n- Type: [`ToOptions`](../ToOptionsType.md)\n- Required\n- The options that will be used to configure the route mask\n\n### `options.routeTree`\n\n- Type: `TRouteTree`\n- Required\n- The route tree that this route mask will support\n\n### `options.unmaskOnReload`\n\n- Type: `boolean`\n- Optional\n- If `true`, the route mask will be removed when the page is reloaded\n\n# RouteMatch type\n\nThe `RouteMatch` type represents a route match in TanStack Router.\n\n```tsx\ninterface RouteMatch {\n id: string\n routeId: string\n pathname: string\n params: Route['allParams']\n status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound'\n isFetching: false | 'beforeLoad' | 'loader'\n showPending: boolean\n error: unknown\n paramsError: unknown\n searchError: unknown\n updatedAt: number\n loaderData?: Route['loaderData']\n context: Route['allContext']\n search: Route['fullSearchSchema']\n fetchedAt: number\n abortController: AbortController\n cause: 'enter' | 'stay'\n ssr?: boolean | 'data-only'\n}\n```\n\n# RouteOptions type\n\nThe `RouteOptions` type is used to describe the options that can be used when creating a route.\n\n## RouteOptions properties\n\nThe `RouteOptions` type accepts an object with the following properties:\n\n### `getParentRoute` method\n\n- Type: `() => TParentRoute`\n- Required\n- A function that returns the parent route of the route being created. This is required to provide full type safety to child route configurations and to ensure that the route tree is built correctly.\n\n### `path` property\n\n- Type: `string`\n- Required, unless an `id` is provided to configure the route as a pathless layout route\n- The path segment that will be used to match the route.\n\n### `id` property\n\n- Type: `string`\n- Optional, but required if a `path` is not provided\n- The unique identifier for the route if it is to be configured as a pathless layout route. If provided, the route will not match against the location pathname and its routes will be flattened into its parent route for matching.\n\n### `component` property\n\n- Type: `RouteComponent` or `LazyRouteComponent`\n- Optional - Defaults to `<Outlet />`\n- The content to be rendered when the route is matched.\n\n### `errorComponent` property\n\n- Type: `RouteComponent` or `LazyRouteComponent`\n- Optional - Defaults to `routerOptions.defaultErrorComponent`\n- The content to be rendered when the route encounters an error.\n\n### `pendingComponent` property\n\n- Type: `RouteComponent` or `LazyRouteComponent`\n- Optional - Defaults to `routerOptions.defaultPendingComponent`\n- The content to be rendered if and when the route is pending and has reached its pendingMs threshold.\n\n### `notFoundComponent` property\n\n- Type: `NotFoundRouteComponent` or `LazyRouteComponent`\n- Optional - Defaults to `routerOptions.defaultNotFoundComponent`\n- The content to be rendered when the route is not found.\n\n### `validateSearch` method\n\n- Type: `(rawSearchParams: unknown) => TSearchSchema`\n- Optional\n- A function that will be called when this route is matched and passed the raw search params from the current location and return valid parsed search params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's search params and the return type will be inferred into the rest of the router.\n- Optionally, the parameter type can be tagged with the `SearchSchemaInput` type like this: `(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema`. If this tag is present, `TSearchSchemaInput` will be used to type the `search` property of `<Link />` and `navigate()` **instead of** `TSearchSchema`. The difference between `TSearchSchemaInput` and `TSearchSchema` can be useful, for example, to express optional search parameters.\n\n### `search.middlewares` property\n\n- Type: `(({search: TSearchSchema, next: (newSearch: TSearchSchema) => TSearchSchema}) => TSearchSchema)[]`\n- Optional\n- Search middlewares are functions that transform the search parameters when generating new links for a route or its descendants.\n- A search middleware is passed in the current search (if it is the first middleware to run) or is invoked by the previous middleware calling `next`.\n\n### `parseParams` method (\u26A0\uFE0F deprecated, use `params.parse` instead)\n\n- Type: `(rawParams: Record<string, string>) => TParams`\n- Optional\n- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.\n\n### `stringifyParams` method (\u26A0\uFE0F deprecated, use `params.stringify` instead)\n\n- Type: `(params: TParams) => Record<string, string>`\n- Required if `parseParams` is provided\n- A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of `Record<string, string>` mapping.\n\n### `params.parse` method\n\n- Type: `(rawParams: Record<string, string>) => TParams`\n- Optional\n- A function that will be called when this route is matched and passed the raw params from the current location and return valid parsed params. If this function throws, the route will be put into an error state and the error will be thrown during render. If this function does not throw, its return value will be used as the route's params and the return type will be inferred into the rest of the router.\n\n### `params.stringify` method\n\n- Type: `(params: TParams) => Record<string, string>`\n- A function that will be called when this route's parsed params are being used to build a location. This function should return a valid object of `Record<string, string>` mapping.\n\n### `beforeLoad` method\n\n- Type:\n\n```tsx\ntype beforeLoad = (\n opts: RouteMatch & {\n search: TFullSearchSchema\n abortController: AbortController\n preload: boolean\n params: TAllParams\n context: TParentContext\n location: ParsedLocation\n navigate: NavigateFn<AnyRoute> // @deprecated\n buildLocation: BuildLocationFn<AnyRoute>\n cause: 'enter' | 'stay'\n },\n) => Promise<TRouteContext> | TRouteContext | void\n```\n\n- Optional\n- [`ParsedLocation`](../ParsedLocationType.md)\n- This async function is called before a route is loaded. If an error is thrown here, the route's loader will not be called and the route will not render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail.\n- If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.\n- If this function returns a `TRouteContext` object, that object will be merged into the route's context and be made available in the `loader` and other related route components/methods.\n- It's common to use this function to check if a user is authenticated and redirect them to a login page if they are not. To do this, you can either return or throw a `redirect` object from this function.\n\n> \uD83D\uDEA7 `opts.navigate` has been deprecated and will be removed in the next major release. Use `throw redirect({ to: '/somewhere' })` instead. Read more about the `redirect` function [here](../redirectFunction.md).\n\n### `loader` method\n\n- Type:\n\n```tsx\ntype loader = (\n opts: RouteMatch & {\n abortController: AbortController\n cause: 'preload' | 'enter' | 'stay'\n context: TAllContext\n deps: TLoaderDeps\n location: ParsedLocation\n params: TAllParams\n preload: boolean\n parentMatchPromise: Promise<MakeRouteMatchFromRoute<TParentRoute>>\n navigate: NavigateFn<AnyRoute> // @deprecated\n route: AnyRoute\n },\n) => Promise<TLoaderData> | TLoaderData | void\n```\n\n- Optional\n- [`ParsedLocation`](../ParsedLocationType.md)\n- This async function is called when a route is matched and passed the route's match object. If an error is thrown here, the route will be put into an error state and the error will be thrown during render. If thrown during a navigation, the navigation will be canceled and the error will be passed to the `onError` function. If thrown during a preload event, the error will be logged to the console and the preload will fail.\n- If this function returns a promise, the route will be put into a pending state and cause rendering to suspend until the promise resolves. If this route's pendingMs threshold is reached, the `pendingComponent` will be shown until it resolves. If the promise rejects, the route will be put into an error state and the error will be thrown during render.\n- If this function returns a `TLoaderData` object, that object will be stored on the route match until the route match is no longer active. It can be accessed using the `useLoaderData` hook in any component that is a child of the route match before another `<Outlet />` is rendered.\n- Deps must be returned by your `loaderDeps` function in order to appear.\n\n> \uD83D\uDEA7 `opts.navigate` has been deprecated and will be removed in the next major release. Use `throw redirect({ to: '/somewhere' })` instead. Read more about the `redirect` function [here](../redirectFunction.md).\n\n### `loaderDeps` method\n\n- Type:\n\n```tsx\ntype loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>\n```\n\n- Optional\n- A function that will be called before this route is matched to provide additional unique identification to the route match and serve as a dependency tracker for when the match should be reloaded. It should return any serializable value that can uniquely identify the route match from navigation to navigation.\n- By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here.\n- If your route match relies on search params for unique identification, it's required that you return them here so they can be made available in the `loader`'s `deps` argument.\n\n### `staleTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultStaleTime`, which defaults to `0`\n- The amount of time in milliseconds that a route match's loader data will be considered fresh. If a route match is matched again within this time frame, its loader data will not be reloaded.\n\n### `preloadStaleTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultPreloadStaleTime`, which defaults to `30_000` ms (30 seconds)\n- The amount of time in milliseconds that a route match's loader data will be considered fresh when preloading. If a route match is preloaded again within this time frame, its loader data will not be reloaded. If a route match is loaded (for navigation) within this time frame, the normal `staleTime` is used instead.\n\n### `gcTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes.\n- The amount of time in milliseconds that a route match's loader data will be kept in memory after a preload or it is no longer in use.\n\n### `shouldReload` property\n\n- Type: `boolean | ((args: LoaderArgs) => boolean)`\n- Optional\n- If `false` or returns `false`, the route match's loader data will not be reloaded on subsequent matches.\n- If `true` or returns `true`, the route match's loader data will be reloaded on subsequent matches.\n- If `undefined` or returns `undefined`, the route match's loader data will adhere to the default stale-while-revalidate behavior.\n\n### `caseSensitive` property\n\n- Type: `boolean`\n- Optional\n- If `true`, this route will be matched as case-sensitive.\n\n### `wrapInSuspense` property\n\n- Type: `boolean`\n- Optional\n- If `true`, this route will be forcefully wrapped in a suspense boundary, regardless if a reason is found to do so from inspecting its provided components.\n\n### `pendingMs` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultPendingMs`, which defaults to `1000`\n- The threshold in milliseconds that a route must be pending before its `pendingComponent` is shown.\n\n### `pendingMinMs` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultPendingMinMs` which defaults to `500`\n- The minimum amount of time in milliseconds that the pending component will be shown for if it is shown. This is useful to prevent the pending component from flashing on the screen for a split second.\n\n### `preloadMaxAge` property\n\n- Type: `number`\n- Optional\n- Defaults to `30_000` ms (30 seconds)\n- The maximum amount of time in milliseconds that a route's preloaded route data will be cached for. If a route is not matched within this time frame, its loader data will be discarded.\n\n### `preSearchFilters` property (\u26A0\uFE0F deprecated, use `search.middlewares` instead)\n\n- Type: `((search: TFullSearchSchema) => TFullSearchSchema)[]`\n- Optional\n- An array of functions that will be called when generating any new links to this route or its grandchildren.\n- Each function will be called with the current search params and should return a new search params object that will be used to generate the link.\n- It has a `pre` prefix because it is called before the user-provided function that is passed to `navigate`/`Link` etc has a chance to modify the search params.\n\n### `postSearchFilters` property (\u26A0\uFE0F deprecated, use `search.middlewares` instead)\n\n- Type: `((search: TFullSearchSchema) => TFullSearchSchema)[]`\n- Optional\n- An array of functions that will be called when generating any new links to this route or its grandchildren.\n- Each function will be called with the current search params and should return a new search params object that will be used to generate the link.\n- It has a `post` prefix because it is called after the user-provided function that is passed to `navigate`/`Link` etc has modified the search params.\n\n### `onError` property\n\n- Type: `(error: any) => void`\n- Optional\n- A function that will be called when an error is thrown during a navigation or preload event.\n- If this function throws a [`redirect`](../redirectFunction.md), then the router will process and apply the redirect immediately.\n\n### `onEnter` property\n\n- Type: `(match: RouteMatch) => void`\n- Optional\n- A function that will be called when a route is matched and loaded after not being matched in the previous location.\n\n### `onStay` property\n\n- Type: `(match: RouteMatch) => void`\n- Optional\n- A function that will be called when a route is matched and loaded after being matched in the previous location.\n\n### `onLeave` property\n\n- Type: `(match: RouteMatch) => void`\n- Optional\n- A function that will be called when a route is no longer matched after being matched in the previous location.\n\n### `onCatch` property\n\n- Type: `(error: Error, errorInfo: ErrorInfo) => void`\n- Optional - Defaults to `routerOptions.defaultOnCatch`\n- A function that will be called when errors are caught when the route encounters an error.\n\n### `remountDeps` method\n\n- Type:\n\n```tsx\ntype remountDeps = (opts: RemountDepsOptions) => any\n\ninterface RemountDepsOptions<\n in out TRouteId,\n in out TFullSearchSchema,\n in out TAllParams,\n in out TLoaderDeps,\n> {\n routeId: TRouteId\n search: TFullSearchSchema\n params: TAllParams\n loaderDeps: TLoaderDeps\n}\n```\n\n- Optional\n- A function that will be called to determine whether a route component shall be remounted after navigation. If this function returns a different value than previously, it will remount.\n- The return value needs to be JSON serializable.\n- By default, a route component will not be remounted if it stays active after a navigation.\n\nExample:\nIf you want to configure to remount a route component upon `params` change, use:\n\n```tsx\nremountDeps: ({ params }) => params\n```\n\n### `headers` method\n\n- Type:\n\n```tsx\ntype headers = (opts: {\n matches: Array<RouteMatch>\n match: RouteMatch\n params: TAllParams\n loaderData?: TLoaderData\n}) => Promise<Record<string, string>> | Record<string, string>\n```\n\n- Optional\n- Allows you to specify custom HTTP headers to be sent when this route is rendered during SSR. The function receives the current match context and should return a plain object of header name/value pairs.\n\n### `head` method\n\n- Type:\n\n```tsx\ntype head = (ctx: {\n matches: Array<RouteMatch>\n match: RouteMatch\n params: TAllParams\n loaderData?: TLoaderData\n}) =>\n | Promise<{\n links?: RouteMatch['links']\n scripts?: RouteMatch['headScripts']\n meta?: RouteMatch['meta']\n styles?: RouteMatch['styles']\n }>\n | {\n links?: RouteMatch['links']\n scripts?: RouteMatch['headScripts']\n meta?: RouteMatch['meta']\n styles?: RouteMatch['styles']\n }\n```\n\n- Optional\n- Returns additional elements to inject into the document `<head>` for this route. Use it to add route-level SEO metadata, preload links, inline styles, or custom scripts.\n\n### `scripts` method\n\n- Type:\n\n```tsx\ntype scripts = (ctx: {\n matches: Array<RouteMatch>\n match: RouteMatch\n params: TAllParams\n loaderData?: TLoaderData\n}) => Promise<RouteMatch['scripts']> | RouteMatch['scripts']\n```\n\n- Optional\n- A shorthand helper to return only `<script>` elements. Equivalent to returning the `scripts` field from the `head` method.\n\n### `codeSplitGroupings` property\n\n- Type: `Array<Array<'loader' | 'component' | 'pendingComponent' | 'notFoundComponent' | 'errorComponent'>>`\n- Optional\n- Fine-grained control over how the router groups lazy-loaded pieces of a route into chunks. Each inner array represents a group of assets that will be placed into the same bundle during code-splitting.\n\n# Route type\n\nThe `Route` type is used to describe a route instance.\n\n## `Route` properties and methods\n\nAn instance of the `Route` has the following properties and methods:\n\n### `.addChildren` method\n\n- Type: `(children: Route[]) => this`\n- Adds child routes to the route instance and returns the route instance (but with updated types to reflect the new children).\n\n### `.update` method\n\n- Type: `(options: Partial<UpdatableRouteOptions>) => this`\n- Updates the route instance with new options and returns the route instance (but with updated types to reflect the new options).\n- In some circumstances, it can be useful to update a route instance's options after it has been created to avoid circular type references.\n- ...`RouteApi` methods\n\n### `.lazy` method\n\n- Type: `(lazyImporter: () => Promise<Partial<UpdatableRouteOptions>>) => this`\n- Updates the route instance with a new lazy importer which will be resolved lazily when loading the route. This can be useful for code splitting.\n\n### ...`RouteApi` methods\n\n- All of the methods from [`RouteApi`](../RouteApiType.md) are available.\n\n# Router Class\n\n> [!CAUTION]\n> This class has been deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createRouter`](../createRouterFunction.md) function instead.\n\nThe `Router` class is used to instantiate a new router instance.\n\n## `Router` constructor\n\nThe `Router` constructor accepts a single argument: the `options` that will be used to configure the router instance.\n\n### Constructor options\n\n- Type: [`RouterOptions`](../RouterOptionsType.md)\n- Required\n- The options that will be used to configure the router instance.\n\n### Constructor returns\n\n- An instance of the [`Router`](../RouterType.md).\n\n## Examples\n\n```tsx\nimport { Router, RouterProvider } from '@tanstack/react-router'\nimport { routeTree } from './routeTree.gen'\n\nconst router = new Router({\n routeTree,\n defaultPreload: 'intent',\n})\n\nexport default function App() {\n return <RouterProvider router={router} />\n}\n```\n\n# RouterEvents type\n\nThe `RouterEvents` type contains all of the events that the router can emit. Each top-level key of this type, represents the name of an event that the router can emit. The values of the keys are the event payloads.\n\n```tsx\ntype RouterEvents = {\n onBeforeNavigate: {\n type: 'onBeforeNavigate'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onBeforeLoad: {\n type: 'onBeforeLoad'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onLoad: {\n type: 'onLoad'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onResolved: {\n type: 'onResolved'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onBeforeRouteMount: {\n type: 'onBeforeRouteMount'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n }\n onInjectedHtml: {\n type: 'onInjectedHtml'\n promise: Promise<string>\n }\n onRendered: {\n type: 'onRendered'\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n }\n}\n```\n\n## RouterEvents properties\n\nOnce an event is emitted, the following properties will be present on the event payload.\n\n### `type` property\n\n- Type: `onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved`\n- The type of the event\n- This is useful for discriminating between events in a listener function.\n\n### `fromLocation` property\n\n- Type: [`ParsedLocation`](../ParsedLocationType.md)\n- The location that the router is transitioning from.\n\n### `toLocation` property\n\n- Type: [`ParsedLocation`](../ParsedLocationType.md)\n- The location that the router is transitioning to.\n\n### `pathChanged` property\n\n- Type: `boolean`\n- `true` if the path has changed between the `fromLocation` and `toLocation`.\n\n### `hrefChanged` property\n\n- Type: `boolean`\n- `true` if the href has changed between the `fromLocation` and `toLocation`.\n\n## Example\n\n```tsx\nimport { createRouter } from '@tanstack/react-router'\nimport { routeTree } from './routeTree.gen'\n\nconst router = createRouter({ routeTree })\n\nconst unsub = router.subscribe('onResolved', (evt) => {\n // ...\n})\n```\n\n# RouterOptions\n\nThe `RouterOptions` type contains all of the options that can be used to configure a router instance.\n\n## RouterOptions properties\n\nThe `RouterOptions` type accepts an object with the following properties and methods:\n\n### `routeTree` property\n\n- Type: `AnyRoute`\n- Required\n- The route tree that will be used to configure the router instance.\n\n### `history` property\n\n- Type: `RouterHistory`\n- Optional\n- The history object that will be used to manage the browser history. If not provided, a new `createBrowserHistory` instance will be created and used.\n\n### `stringifySearch` method\n\n- Type: `(search: Record<string, any>) => string`\n- Optional\n- A function that will be used to stringify search params when generating links.\n- Defaults to `defaultStringifySearch`.\n\n### `parseSearch` method\n\n- Type: `(search: string) => Record<string, any>`\n- Optional\n- A function that will be used to parse search params when parsing the current location.\n- Defaults to `defaultParseSearch`.\n\n### `search.strict` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- Configures how unknown search params (= not returned by any `validateSearch`) are treated.\n- If `false`, unknown search params will be kept.\n- If `true`, unknown search params will be removed.\n\n### `defaultPreload` property\n\n- Type: `undefined | false | 'intent' | 'viewport' | 'render'`\n- Optional\n- Defaults to `false`\n- If `false`, routes will not be preloaded by default in any way.\n- If `'intent'`, routes will be preloaded by default when the user hovers over a link or a `touchstart` event is detected on a `<Link>`.\n- If `'viewport'`, routes will be preloaded by default when they are within the viewport of the browser.\n- If `'render'`, routes will be preloaded by default as soon as they are rendered in the DOM.\n\n### `defaultPreloadDelay` property\n\n- Type: `number`\n- Optional\n- Defaults to `50`\n- The delay in milliseconds that a route must be hovered over or touched before it is preloaded.\n\n### `defaultComponent` property\n\n- Type: `RouteComponent`\n- Optional\n- Defaults to `Outlet`\n- The default `component` a route should use if no component is provided.\n\n### `defaultErrorComponent` property\n\n- Type: `RouteComponent`\n- Optional\n- Defaults to `ErrorComponent`\n- The default `errorComponent` a route should use if no error component is provided.\n\n### `defaultNotFoundComponent` property\n\n- Type: `NotFoundRouteComponent`\n- Optional\n- Defaults to `NotFound`\n- The default `notFoundComponent` a route should use if no notFound component is provided.\n\n### `defaultPendingComponent` property\n\n- Type: `RouteComponent`\n- Optional\n- The default `pendingComponent` a route should use if no pending component is provided.\n\n### `defaultPendingMs` property\n\n- Type: `number`\n- Optional\n- Defaults to `1000`\n- The default `pendingMs` a route should use if no pendingMs is provided.\n\n### `defaultPendingMinMs` property\n\n- Type: `number`\n- Optional\n- Defaults to `500`\n- The default `pendingMinMs` a route should use if no pendingMinMs is provided.\n\n### `defaultStaleTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `0`\n- The default `staleTime` a route should use if no staleTime is provided.\n\n### `defaultPreloadStaleTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `30_000` ms (30 seconds)\n- The default `preloadStaleTime` a route should use if no preloadStaleTime is provided.\n\n### `defaultPreloadGcTime` property\n\n- Type: `number`\n- Optional\n- Defaults to `routerOptions.defaultGcTime`, which defaults to 30 minutes.\n- The default `preloadGcTime` a route should use if no preloadGcTime is provided.\n\n### `defaultGcTime` property\n\n- Type: `number`\n- Optional\n- Defaults to 30 minutes.\n- The default `gcTime` a route should use if no gcTime is provided.\n\n### `defaultOnCatch` property\n\n- Type: `(error: Error, errorInfo: ErrorInfo) => void`\n- Optional\n- The default `onCatch` handler for errors caught by the Router ErrorBoundary\n\n### `disableGlobalCatchBoundary` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- When `true`, disables the global catch boundary that normally wraps all route matches. This allows unhandled errors to bubble up to top-level error handlers in the browser.\n- Useful for testing tools, error reporting services, and debugging scenarios.\n\n### `defaultViewTransition` property\n\n- Type: `boolean | ViewTransitionOptions`\n- Optional\n- If `true`, route navigations will be called using `document.startViewTransition()`.\n- If [`ViewTransitionOptions`](../ViewTransitionOptionsType.md), route navigations will be called using `document.startViewTransition({update, types})`\n where `types` will be the strings array passed with `ViewTransitionOptions[\"types\"]`. If the browser does not support viewTransition types,\n the navigation will fall back to normal `document.startTransition()`, same as if `true` was passed.\n- If the browser does not support this api, this option will be ignored.\n- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.\n- See [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types) for more information on viewTransition types\n\n### `defaultHashScrollIntoView` property\n\n- Type: `boolean | ScrollIntoViewOptions`\n- Optional\n- Defaults to `true` so the element with an id matching the hash will be scrolled into view after the location is committed to history.\n- If `false`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.\n- If an object is provided, it will be passed to the `scrollIntoView` method as options.\n- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on `ScrollIntoViewOptions`.\n\n### `caseSensitive` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- If `true`, all routes will be matched as case-sensitive.\n\n### `basepath` property\n\n- Type: `string`\n- Optional\n- Defaults to `/`\n- The basepath for the entire router. This is useful for mounting a router instance at a subpath.\n\n### `context` property\n\n- Type: `any`\n- Optional or required if the root route was created with [`createRootRouteWithContext()`](../createRootRouteWithContextFunction.md).\n- The root context that will be provided to all routes in the route tree. This can be used to provide a context to all routes in the tree without having to provide it to each route individually.\n\n### `dehydrate` method\n\n- Type: `() => TDehydrated`\n- Optional\n- A function that will be called when the router is dehydrated. The return value of this function will be serialized and stored in the router's dehydrated state.\n\n### `hydrate` method\n\n- Type: `(dehydrated: TDehydrated) => void`\n- Optional\n- A function that will be called when the router is hydrated. The return value of this function will be serialized and stored in the router's dehydrated state.\n\n### `routeMasks` property\n\n- Type: `RouteMask[]`\n- Optional\n- An array of route masks that will be used to mask routes in the route tree. Route masking is when you display a route at a different path than the one it is configured to match, like a modal popup that when shared will unmask to the modal's content instead of the modal's context.\n\n### `unmaskOnReload` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- If `true`, route masks will, by default, be removed when the page is reloaded. This can be overridden on a per-mask basis by setting the `unmaskOnReload` option on the mask, or on a per-navigation basis by setting the `unmaskOnReload` option in the `Navigate` options.\n\n### `Wrap` property\n\n- Type: `React.Component`\n- Optional\n- A component that will be used to wrap the entire router. This is useful for providing a context to the entire router. Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.\n\n**Example**\n\n```tsx\nimport { createRouter } from '@tanstack/react-router'\n\nconst router = createRouter({\n // ...\n Wrap: ({ children }) => {\n return <MyContext.Provider value={myContext}>{children}</MyContext>\n },\n})\n```\n\n### `InnerWrap` property\n\n- Type: `React.Component`\n- Optional\n- A component that will be used to wrap the inner contents of the router. This is useful for providing a context to the inner contents of the router where you also need access to the router context and hooks. Only non-DOM-rendering components like providers should be used, anything else will cause a hydration error.\n\n**Example**\n\n```tsx\nimport { createRouter } from '@tanstack/react-router'\n\nconst router = createRouter({\n // ...\n InnerWrap: ({ children }) => {\n const routerState = useRouterState()\n\n return (\n <MyContext.Provider value={myContext}>\n {children}\n </MyContext>\n )\n },\n})\n```\n\n### `notFoundMode` property\n\n- Type: `'root' | 'fuzzy'`\n- Optional\n- Defaults to `'fuzzy'`\n- This property controls how TanStack Router will handle scenarios where it cannot find a route to match the current location. See the [Not Found Errors guide](../../../guide/not-found-errors.md) for more information.\n\n### `notFoundRoute` property\n\n- **Deprecated**\n- Type: `NotFoundRoute`\n- Optional\n- A route that will be used as the default not found route for every branch of the route tree. This can be overridden on a per-branch basis by providing a not found route to the `NotFoundRoute` option on the root route of the branch.\n\n### `trailingSlash` property\n\n- Type: `'always' | 'never' | 'preserve'`\n- Optional\n- Defaults to `never`\n- Configures how trailing slashes are treated. `'always'` will add a trailing slash if not present, `'never'` will remove the trailing slash if present and `'preserve'` will not modify the trailing slash.\n\n### `pathParamsAllowedCharacters` property\n\n- Type: `Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>`\n- Optional\n- Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent.\n\n### `defaultStructuralSharing` property\n\n- Type: `boolean`\n- Optional\n- Defaults to `false`\n- Configures whether structural sharing is enabled by default for fine-grained selectors.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n### `defaultRemountDeps` property\n\n- Type:\n\n```tsx\ntype defaultRemountDeps = (opts: RemountDepsOptions) => any\n\ninterface RemountDepsOptions<\n in out TRouteId,\n in out TFullSearchSchema,\n in out TAllParams,\n in out TLoaderDeps,\n> {\n routeId: TRouteId\n search: TFullSearchSchema\n params: TAllParams\n loaderDeps: TLoaderDeps\n}\n```\n\n- Optional\n- A default function that will be called to determine whether a route component shall be remounted after navigation. If this function returns a different value than previously, it will remount.\n- The return value needs to be JSON serializable.\n- By default, a route component will not be remounted if it stays active after a navigation\n\nExample: \nIf you want to configure to remount all route components upon `params` change, use:\n\n```tsx\nremountDeps: ({ params }) => params\n```\n\n# RouterState type\n\nThe `RouterState` type represents shape of the internal state of the router. The Router's internal state is useful, if you need to access certain internals of the router, such as any pending matches, is the router in its loading state, etc.\n\n```tsx\ntype RouterState = {\n status: 'pending' | 'idle'\n isLoading: boolean\n isTransitioning: boolean\n matches: Array<RouteMatch>\n pendingMatches: Array<RouteMatch>\n location: ParsedLocation\n resolvedLocation: ParsedLocation\n}\n```\n\n## RouterState properties\n\nThe `RouterState` type contains all of the properties that are available on the router state.\n\n### `status` property\n\n- Type: `'pending' | 'idle'`\n- The current status of the router. If the router is pending, it means that it is currently loading a route or the router is still transitioning to the new route.\n\n### `isLoading` property\n\n- Type: `boolean`\n- `true` if the router is currently loading a route or waiting for a route to finish loading.\n\n### `isTransitioning` property\n\n- Type: `boolean`\n- `true` if the router is currently transitioning to a new route.\n\n### `matches` property\n\n- Type: [`Array<RouteMatch>`](../RouteMatchType.md)\n- An array of all of the route matches that have been resolved and are currently active.\n\n### `pendingMatches` property\n\n- Type: [`Array<RouteMatch>`](../RouteMatchType.md)\n- An array of all of the route matches that are currently pending.\n\n### `location` property\n\n- Type: [`ParsedLocation`](../ParsedLocationType.md)\n- The latest location that the router has parsed from the browser history. This location may not be resolved and loaded yet.\n\n### `resolvedLocation` property\n\n- Type: [`ParsedLocation`](../ParsedLocationType.md)\n- The location that the router has resolved and loaded.\n\n# Router type\n\nThe `Router` type is used to describe a router instance.\n\n## `Router` properties and methods\n\nAn instance of the `Router` has the following properties and methods:\n\n### `.update` method\n\n- Type: `(newOptions: RouterOptions) => void`\n- Updates the router instance with new options.\n\n### `state` property\n\n- Type: [`RouterState`](../RouterStateType.md)\n- The current state of the router.\n\n> \u26A0\uFE0F\u26A0\uFE0F\u26A0\uFE0F **`router.state` is always up to date, but NOT REACTIVE. If you use `router.state` in a component, the component will not re-render when the router state changes. To get a reactive version of the router state, use the [`useRouterState`](../useRouterStateHook.md) hook.**\n\n### `.subscribe` method\n\n- Type: `(eventType: TType, fn: ListenerFn<RouterEvents[TType]>) => (event: RouterEvent) => void`\n- Subscribes to a [`RouterEvent`](../RouterEventsType.md).\n- Returns a function that can be used to unsubscribe from the event.\n- The callback provided to the returned function will be called with the event that was emitted.\n\n### `.matchRoutes` method\n\n- Type: `(pathname: string, locationSearch?: Record<string, any>, opts?: { throwOnError?: boolean; }) => RouteMatch[]`\n- Matches a pathname and search params against the router's route tree and returns an array of route matches.\n- If `opts.throwOnError` is `true`, any errors that occur during the matching process will be thrown (in addition to being returned in the route match's `error` property).\n\n### `.cancelMatch` method\n\n- Type: `(matchId: string) => void`\n- Cancels a route match that is currently pending by calling `match.abortController.abort()`.\n\n### `.cancelMatches` method\n\n- Type: `() => void`\n- Cancels all route matches that are currently pending by calling `match.abortController.abort()` on each one.\n\n### `.buildLocation` method\n\nBuilds a new parsed location object that can be used later to navigate to a new location.\n\n- Type: `(opts: BuildNextOptions) => ParsedLocation`\n- Properties\n - `from`\n - Type: `string`\n - Optional\n - The path to navigate from. If not provided, the current path will be used.\n - `to`\n - Type: `string | number | null`\n - Optional\n - The path to navigate to. If `null`, the current path will be used.\n - `params`\n - Type: `true | Updater<unknown>`\n - Optional\n - If `true`, the current params will be used. If a function is provided, it will be called with the current params and the return value will be used.\n - `search`\n - Type: `true | Updater<unknown>`\n - Optional\n - If `true`, the current search params will be used. If a function is provided, it will be called with the current search params and the return value will be used.\n - `hash`\n - Type: `true | Updater<string>`\n - Optional\n - If `true`, the current hash will be used. If a function is provided, it will be called with the current hash and the return value will be used.\n - `state`\n - Type: `true | NonNullableUpdater<ParsedHistoryState, HistoryState>`\n - Optional\n - If `true`, the current state will be used. If a function is provided, it will be called with the current state and the return value will be used.\n - `mask`\n - Type: `object`\n - Optional\n - Contains all of the same BuildNextOptions, with the addition of `unmaskOnReload`.\n - `unmaskOnReload`\n - Type: `boolean`\n - Optional\n - If `true`, the route mask will be removed when the page is reloaded. This can be overridden on a per-navigation basis by setting the `unmaskOnReload` option in the `Navigate` options.\n\n### `.commitLocation` method\n\nCommits a new location object to the browser history.\n\n- Type\n ```tsx\n type commitLocation = (\n location: ParsedLocation & {\n replace?: boolean\n resetScroll?: boolean\n hashScrollIntoView?: boolean | ScrollIntoViewOptions\n ignoreBlocker?: boolean\n },\n ) => Promise<void>\n ```\n- Properties\n - `location`\n - Type: [`ParsedLocation`](../ParsedLocationType.md)\n - Required\n - The location to commit to the browser history.\n - `replace`\n - Type: `boolean`\n - Optional\n - Defaults to `false`.\n - If `true`, the location will be committed to the browser history using `history.replace` instead of `history.push`.\n - `resetScroll`\n - Type: `boolean`\n - Optional\n - Defaults to `true` so that the scroll position will be reset to 0,0 after the location is committed to the browser history.\n - If `false`, the scroll position will not be reset to 0,0 after the location is committed to history.\n - `hashScrollIntoView`\n - Type: `boolean | ScrollIntoViewOptions`\n - Optional\n - Defaults to `true` so the element with an id matching the hash will be scrolled into view after the location is committed to history.\n - If `false`, the element with an id matching the hash will not be scrolled into view after the location is committed to history.\n - If an object is provided, it will be passed to the `scrollIntoView` method as options.\n - See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView) for more information on `ScrollIntoViewOptions`.\n - `ignoreBlocker`\n - Type: `boolean`\n - Optional\n - Defaults to `false`.\n - If `true`, navigation will ignore any blockers that might prevent it.\n\n### `.navigate` method\n\nNavigates to a new location.\n\n- Type\n ```tsx\n type navigate = (options: NavigateOptions) => Promise<void>\n ```\n\n### `.invalidate` method\n\nInvalidates route matches by forcing their `beforeLoad` and `load` functions to be called again.\n\n- Type: `(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean, sync?: boolean, forcePending?: boolean }) => Promise<void>`\n- This is useful any time your loader data might be out of date or stale. For example, if you have a route that displays a list of posts, and you have a loader function that fetches the list of posts from an API, you might want to invalidate the route matches for that route any time a new post is created so that the list of posts is always up-to-date.\n- if `filter` is not supplied, all matches will be invalidated\n- if `filter` is supplied, only matches for which `filter` returns `true` will be invalidated.\n- if `sync` is true, the promise returned by this function will only resolve once all loaders have finished.\n- if `forcePending` is true, the invalidated matches will be put into `'pending'` state regardless whether they are in `'error'` state or not.\n- You might also want to invalidate the Router if you imperatively `reset` the router's `CatchBoundary` to trigger loaders again.\n\n### `.clearCache` method\n\nRemove cached route matches.\n\n- Type: `(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean}) => void`\n- if `filter` is not supplied, all cached matches will be removed\n- if `filter` is supplied, only matches for which `filter` returns `true` will be removed.\n\n### `.load` method\n\nLoads all of the currently matched route matches and resolves when they are all loaded and ready to be rendered.\n\n> \u26A0\uFE0F\u26A0\uFE0F\u26A0\uFE0F **`router.load()` respects `route.staleTime` and will not forcefully reload a route match if it is still fresh. If you need to forcefully reload a route match, use `router.invalidate()` instead.**\n\n- Type: `(opts?: {sync?: boolean}) => Promise<void>`\n- if `sync` is true, the promise returned by this function will only resolve once all loaders have finished.\n- The most common use case for this method is to call it when doing SSR to ensure that all of the critical data for the current route is loaded before attempting to stream or render the application to the client.\n\n### `.preloadRoute` method\n\nPreloads all of the matches that match the provided `NavigateOptions`.\n\n> \u26A0\uFE0F\u26A0\uFE0F\u26A0\uFE0F **Preloaded route matches are not stored long-term in the router state. They are only stored until the next attempted navigation action.**\n\n- Type: `(opts?: NavigateOptions) => Promise<RouteMatch[]>`\n- Properties\n - `opts`\n - Type: `NavigateOptions`\n - Optional, defaults to the current location.\n - The options that will be used to determine which route matches to preload.\n- Returns\n - A promise that resolves with an array of all of the route matches that were preloaded.\n\n### `.loadRouteChunk` method\n\nLoads the JS chunk of the route.\n\n- Type: `(route: AnyRoute) => Promise<void>`\n\n### `.matchRoute` method\n\nMatches a pathname and search params against the router's route tree and returns a route match's params or false if no match was found.\n\n- Type: `(dest: ToOptions, matchOpts?: MatchRouteOptions) => RouteMatch['params'] | false`\n- Properties\n - `dest`\n - Type: `ToOptions`\n - Required\n - The destination to match against.\n - `matchOpts`\n - Type: `MatchRouteOptions`\n - Optional\n - Options that will be used to match the destination.\n- Returns\n - A route match's params if a match was found.\n - `false` if no match was found.\n\n### `.dehydrate` method\n\nDehydrates the router's critical state into a serializable object that can be sent to the client in an initial request.\n\n- Type: `() => DehydratedRouter`\n- Returns\n - A serializable object that contains the router's critical state.\n\n### `.hydrate` method\n\nHydrates the router's critical state from a serializable object that was sent from the server in an initial request.\n\n- Type: `(dehydrated: DehydratedRouter) => void`\n- Properties\n - `dehydrated`\n - Type: `DehydratedRouter`\n - Required\n - The dehydrated router state that was sent from the server.\n\n# ToMaskOptions type\n\nThe `ToMaskOptions` type extends the [`ToOptions`](../ToOptionsType.md) type and describes additional options available when using route masks.\n\n```tsx\ntype ToMaskOptions = ToOptions & {\n unmaskOnReload?: boolean\n}\n```\n\n- [`ToOptions`](../ToOptionsType.md)\n\n# ToOptions type\n\nThe `ToOptions` type contains several properties that can be used to describe a router destination.\n\n```tsx\ntype ToOptions = {\n from?: ValidRoutePath | string\n to?: ValidRoutePath | string\n hash?: true | string | ((prev?: string) => string)\n state?: true | HistoryState | ((prev: HistoryState) => HistoryState)\n} & SearchParamOptions &\n PathParamOptions\n\ntype SearchParamOptions = {\n search?: true | TToSearch | ((prev: TFromSearch) => TToSearch)\n}\n\ntype PathParamOptions = {\n path?: true | Record<string, TPathParam> | ((prev: TFromParams) => TToParams)\n}\n```\n\n# UseMatchRouteOptions type\n\nThe `UseMatchRouteOptions` type extends the [`ToOptions`](../ToOptionsType.md) type and describes additional options available when using the [`useMatchRoute`](../useMatchRouteHook.md) hook.\n\n```tsx\nexport type UseMatchRouteOptions = ToOptions & MatchRouteOptions\n```\n\n- [`ToOptions`](../ToOptionsType.md)\n- [`MatchRouteOptions`](../MatchRouteOptionsType.md)\n\n# ViewTransitionOptions type\n\nThe `ViewTransitionOptions` type is used to define a\n[viewTransition type](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types).\n\n```tsx\ninterface ViewTransitionOptions {\n types:\n | Array<string>\n | ((locationChangeInfo: {\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n hashChanged: boolean\n }) => Array<string> | false)\n}\n```\n\n## ViewTransitionOptions properties\n\nThe `ViewTransitionOptions` type accepts an object with a single property:\n\n### `types` property\n\n- Type: `Array<string> | ((locationChangeInfo: {\n fromLocation?: ParsedLocation\n toLocation: ParsedLocation\n pathChanged: boolean\n hrefChanged: boolean\n hashChanged: boolean\n}) => (Array<string> | false))`\n- Required\n- Either one of:\n - An array of strings that will be passed to the `document.startViewTransition({update, types}) call`\n - A function that accepts `locationChangeInfo` object and returns either:\n - An array of strings that will be passed to the `document.startViewTransition({update, types}) call`\n - or `false` to skip the view transition\n\n# Await component\n\nThe `Await` component is a component that suspends until the provided promise is resolved or rejected.\nThis is only necessary for React 18.\nIf you are using React 19, you can use the `use()` hook instead.\n\n## Await props\n\nThe `Await` component accepts the following props:\n\n### `props.promise` prop\n\n- Type: `Promise<T>`\n- Required\n- The promise to await.\n\n### `props.children` prop\n\n- Type: `(result: T) => React.ReactNode`\n- Required\n- A function that will be called with the resolved value of the promise.\n\n## Await returns\n\n- Throws an error if the promise is rejected.\n- Suspends (throws a promise) if the promise is pending.\n- Returns the resolved value of a deferred promise if the promise is resolved using `props.children` as the render function.\n\n## Examples\n\n```tsx\nimport { Await } from '@tanstack/react-router'\n\nfunction Component() {\n const { deferredPromise } = route.useLoaderData()\n\n return (\n <Await promise={deferredPromise}>\n {(data) => <div>{JSON.stringify(data)}</div>}\n </Await>\n )\n}\n```\n\n# CatchBoundary component\n\nThe `CatchBoundary` component is a component that catches errors thrown by its children, renders an error component and optionally calls the `onCatch` callback. It also accepts a `getResetKey` function that can be used to declaratively reset the component's state when the key changes.\n\n## CatchBoundary props\n\nThe `CatchBoundary` component accepts the following props:\n\n### `props.getResetKey` prop\n\n- Type: `() => string`\n- Required\n- A function that returns a string that will be used to reset the component's state when the key changes.\n\n### `props.children` prop\n\n- Type: `React.ReactNode`\n- Required\n- The component's children to render when there is no error\n\n### `props.errorComponent` prop\n\n- Type: `React.ReactNode`\n- Optional - [`default: ErrorComponent`](../errorComponentComponent.md)\n- The component to render when there is an error.\n\n### `props.onCatch` prop\n\n- Type: `(error: any) => void`\n- Optional\n- A callback that will be called with the error that was thrown by the component's children.\n\n## CatchBoundary returns\n\n- Returns the component's children if there is no error.\n- Returns the `errorComponent` if there is an error.\n\n## Examples\n\n```tsx\nimport { CatchBoundary } from '@tanstack/react-router'\n\nfunction Component() {\n return (\n <CatchBoundary\n getResetKey={() => 'reset'}\n onCatch={(error) => console.error(error)}\n >\n <div>My Component</div>\n </CatchBoundary>\n )\n}\n```\n\n# CatchNotFound Component\n\nThe `CatchNotFound` component is a component that catches not-found errors thrown by its children, renders a fallback component and optionally calls the `onCatch` callback. It resets when the pathname changes.\n\n## CatchNotFound props\n\nThe `CatchNotFound` component accepts the following props:\n\n### `props.children` prop\n\n- Type: `React.ReactNode`\n- Required\n- The component's children to render when there is no error\n\n### `props.fallback` prop\n\n- Type: `(error: NotFoundError) => React.ReactElement`\n- Optional\n- The component to render when there is an error\n\n### `props.onCatch` prop\n\n- Type: `(error: any) => void`\n- Optional\n- A callback that will be called with the error that was thrown by the component's children\n\n## CatchNotFound returns\n\n- Returns the component's children if there is no error.\n- Returns the `fallback` if there is an error.\n\n## Examples\n\n```tsx\nimport { CatchNotFound } from '@tanstack/react-router'\n\nfunction Component() {\n return (\n <CatchNotFound\n fallback={(error) => <p>Not found error! {JSON.stringify(error)}</p>}\n >\n <ComponentThatMightThrowANotFoundError />\n </CatchNotFound>\n )\n}\n```\n\n# ClientOnly Component\n\nThe `ClientOnly` component is used to render a components only in the client, without breaking the server-side rendering due to hydration errors. It accepts a `fallback` prop that will be rendered if the JS is not yet loaded in the client.\n\n## Props\n\nThe `ClientOnly` component accepts the following props:\n\n### `props.fallback` prop\n\nThe fallback component to render if the JS is not yet loaded in the client.\n\n### `props.children` prop\n\nThe component to render if the JS is loaded in the client.\n\n## Returns\n\n- Returns the component's children if the JS is loaded in the client.\n- Returns the `fallback` component if the JS is not yet loaded in the client.\n\n## Examples\n\n```tsx\n// src/routes/dashboard.tsx\nimport { ClientOnly, createFileRoute } from '@tanstack/react-router'\nimport {\n Charts,\n FallbackCharts,\n} from './charts-that-break-server-side-rendering'\n\nexport const Route = createFileRoute('/dashboard')({\n component: Dashboard,\n // ... other route options\n})\n\nfunction Dashboard() {\n return (\n <div>\n <p>Dashboard</p>\n <ClientOnly fallback={<FallbackCharts />}>\n <Charts />\n </ClientOnly>\n </div>\n )\n}\n```\n\n# createFileRoute function\n\nThe `createFileRoute` function is a factory that can be used to create a file-based route instance. This route instance can then be used to automatically generate a route tree with the `tsr generate` and `tsr watch` commands.\n\n## createFileRoute options\n\nThe `createFileRoute` function accepts a single argument of type `string` that represents the `path` of the file that the route will be generated from.\n\n### `path` option\n\n- Type: `string` literal\n- Required, but **automatically inserted and updated by the `tsr generate` and `tsr watch` commands**\n- The full path of the file that the route will be generated from\n\n## createFileRoute returns\n\nA new function that accepts a single argument of type [`RouteOptions`](../RouteOptionsType.md) that will be used to configure the file [`Route`](../RouteType.md) instance.\n\n> \u26A0\uFE0F Note: For `tsr generate` and `tsr watch` to work properly, the file route instance must be exported from the file using the `Route` identifier.\n\n## Examples\n\n```tsx\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/')({\n loader: () => {\n return 'Hello World'\n },\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# createLazyFileRoute function\n\nThe `createLazyFileRoute` function is used for creating a partial file-based route route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as `component`, `pendingComponent`, `errorComponent`, and the `notFoundComponent`.\n\n## createLazyFileRoute options\n\nThe `createLazyFileRoute` function accepts a single argument of type `string` that represents the `path` of the file that the route will be generated from.\n\n### `path`\n\n- Type: `string`\n- Required, but **automatically inserted and updated by the `tsr generate` and `tsr watch` commands**\n- The full path of the file that the route will be generated from.\n\n### createLazyFileRoute returns\n\nA new function that accepts a single argument of partial of the type [`RouteOptions`](../RouteOptionsType.md) that will be used to configure the file [`Route`](../RouteType.md) instance.\n\n- Type:\n\n```tsx\nPick<\n RouteOptions,\n 'component' | 'pendingComponent' | 'errorComponent' | 'notFoundComponent'\n>\n```\n\n- [`RouteOptions`](../RouteOptionsType.md)\n\n> \u26A0\uFE0F Note: For `tsr generate` and `tsr watch` to work properly, the file route instance must be exported from the file using the `Route` identifier.\n\n### Examples\n\n```tsx\nimport { createLazyFileRoute } from '@tanstack/react-router'\n\nexport const Route = createLazyFileRoute('/')({\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# createLazyRoute function\n\nThe `createLazyRoute` function is used for creating a partial code-based route route instance that is lazily loaded when matched. This route instance can only be used to configure the [non-critical properties](../../../guide/code-splitting.md#how-does-tanstack-router-split-code) of the route, such as `component`, `pendingComponent`, `errorComponent`, and the `notFoundComponent`.\n\n## createLazyRoute options\n\nThe `createLazyRoute` function accepts a single argument of type `string` that represents the `id` of the route.\n\n### `id`\n\n- Type: `string`\n- Required\n- The route id of the route.\n\n### createLazyRoute returns\n\nA new function that accepts a single argument of partial of the type [`RouteOptions`](../RouteOptionsType.md) that will be used to configure the file [`Route`](../RouteType.md) instance.\n\n- Type:\n\n```tsx\nPick<\n RouteOptions,\n 'component' | 'pendingComponent' | 'errorComponent' | 'notFoundComponent'\n>\n```\n\n- [`RouteOptions`](../RouteOptionsType.md)\n\n> \u26A0\uFE0F Note: This route instance must be manually lazily loaded against its critical route instance using the `lazy` method returned by the `createRoute` function.\n\n### Examples\n\n```tsx\n// src/route-pages/index.tsx\nimport { createLazyRoute } from '@tanstack/react-router'\n\nexport const Route = createLazyRoute('/')({\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n\n// src/routeTree.tsx\nimport {\n createRootRouteWithContext,\n createRoute,\n Outlet,\n} from '@tanstack/react-router'\n\ninterface MyRouterContext {\n foo: string\n}\n\nconst rootRoute = createRootRouteWithContext<MyRouterContext>()({\n component: () => <Outlet />,\n})\n\nconst indexRoute = createRoute({\n getParentRoute: () => rootRoute,\n path: '/',\n}).lazy(() => import('./route-pages/index').then((d) => d.Route))\n\nexport const routeTree = rootRoute.addChildren([indexRoute])\n```\n\n# createRootRoute function\n\nThe `createRootRoute` function returns a new root route instance. A root route instance can then be used to create a route-tree.\n\n## createRootRoute options\n\nThe options that will be used to configure the root route instance.\n\n- Type:\n\n```tsx\nOmit<\n RouteOptions,\n | 'path'\n | 'id'\n | 'getParentRoute'\n | 'caseSensitive'\n | 'parseParams'\n | 'stringifyParams'\n>\n```\n\n- [`RouteOptions`](../RouteOptionsType.md)\n- Optional\n\n## createRootRoute returns\n\nA new [`Route`](../RouteType.md) instance.\n\n## Examples\n\n```tsx\nimport { createRootRoute, createRouter, Outlet } from '@tanstack/react-router'\n\nconst rootRoute = createRootRoute({\n component: () => <Outlet />,\n // ... root route options\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst router = createRouter({\n routeTree,\n})\n```\n\n# createRootRouteWithContext function\n\nThe `createRootRouteWithContext` function is a helper function that can be used to create a root route instance that requires a context type to be fulfilled when the router is created.\n\n## createRootRouteWithContext generics\n\nThe `createRootRouteWithContext` function accepts a single generic argument:\n\n### `TRouterContext` generic\n\n- Type: `TRouterContext`\n- Optional, **but recommended**.\n- The context type that will be required to be fulfilled when the router is created\n\n## createRootRouteWithContext returns\n\n- A factory function that can be used to create a new [`createRootRoute`](../createRootRouteFunction.md) instance.\n- It accepts a single argument, the same as the [`createRootRoute`](../createRootRouteFunction.md) function.\n\n## Examples\n\n```tsx\nimport {\n createRootRouteWithContext,\n createRouter,\n} from '@tanstack/react-router'\nimport { QueryClient } from '@tanstack/react-query'\n\ninterface MyRouterContext {\n queryClient: QueryClient\n}\n\nconst rootRoute = createRootRouteWithContext<MyRouterContext>()({\n component: () => <Outlet />,\n // ... root route options\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst queryClient = new QueryClient()\n\nconst router = createRouter({\n routeTree,\n context: {\n queryClient,\n },\n})\n```\n\n# createRoute function\n\nThe `createRoute` function implements returns a [`Route`](../RouteType.md) instance. A route instance can then be passed to a root route's children to create a route tree, which is then passed to the router.\n\n## createRoute options\n\n- Type: [`RouteOptions`](../RouteOptionsType.md)\n- Required\n- The options that will be used to configure the route instance\n\n## createRoute returns\n\nA new [`Route`](../RouteType.md) instance.\n\n## Examples\n\n```tsx\nimport { createRoute } from '@tanstack/react-router'\nimport { rootRoute } from './__root'\n\nconst Route = createRoute({\n getParentRoute: () => rootRoute,\n path: '/',\n loader: () => {\n return 'Hello World'\n },\n component: IndexComponent,\n})\n\nfunction IndexComponent() {\n const data = Route.useLoaderData()\n return <div>{data}</div>\n}\n```\n\n# createRouteMask function\n\nThe `createRouteMask` function is a helper function that can be used to create a route mask configuration that can be passed to the `RouterOptions.routeMasks` option.\n\n## createRouteMask options\n\n- Type: [`RouteMask`](../RouteMaskType.md)\n- Required\n- The options that will be used to configure the route mask\n\n## createRouteMask returns\n\n- A object with the type signature of [`RouteMask`](../RouteMaskType.md) that can be passed to the `RouterOptions.routeMasks` option.\n\n## Examples\n\n```tsx\nimport { createRouteMask, createRouter } from '@tanstack/react-router'\n\nconst photoModalToPhotoMask = createRouteMask({\n routeTree,\n from: '/photos/$photoId/modal',\n to: '/photos/$photoId',\n params: true,\n})\n\n// Set up a Router instance\nconst router = createRouter({\n routeTree,\n routeMasks: [photoModalToPhotoMask],\n})\n```\n\n# createRouter function\n\nThe `createRouter` function accepts a [`RouterOptions`](../RouterOptionsType.md) object and creates a new [`Router`](../RouterClass.md) instance.\n\n## createRouter options\n\n- Type: [`RouterOptions`](../RouterOptionsType.md)\n- Required\n- The options that will be used to configure the router instance.\n\n## createRouter returns\n\n- An instance of the [`Router`](../RouterType.md).\n\n## Examples\n\n```tsx\nimport { createRouter, RouterProvider } from '@tanstack/react-router'\nimport { routeTree } from './routeTree.gen'\n\nconst router = createRouter({\n routeTree,\n defaultPreload: 'intent',\n})\n\nexport default function App() {\n return <RouterProvider router={router} />\n}\n```\n\n# DefaultGlobalNotFound component\n\nThe `DefaultGlobalNotFound` component is a component that renders \"Not Found\" on the root route when there is no other route that matches and a `notFoundComponent` is not provided.\n\n## DefaultGlobalNotFound returns\n\n```tsx\n<p>Not Found</p>\n```\n\n# defer function\n\n> [!CAUTION]\n> You don't need to call `defer` manually anymore, Promises are handled automatically now.\n\nThe `defer` function wraps a promise with a deferred state object that can be used to inspect the promise's state. This deferred promise can then be passed to the [`useAwaited`](../useAwaitedHook.md) hook or the [`<Await>`](../awaitComponent.md) component for suspending until the promise is resolved or rejected.\n\nThe `defer` function accepts a single argument, the `promise` to wrap with a deferred state object.\n\n## defer options\n\n- Type: `Promise<T>`\n- Required\n- The promise to wrap with a deferred state object.\n\n## defer returns\n\n- A promise that can be passed to the [`useAwaited`](../useAwaitedHook.md) hook or the [`<Await>`](../awaitComponent.md) component.\n\n## Examples\n\n```tsx\nimport { defer } from '@tanstack/react-router'\n\nconst route = createRoute({\n loader: () => {\n const deferredPromise = defer(fetch('/api/data'))\n return { deferredPromise }\n },\n component: MyComponent,\n})\n\nfunction MyComponent() {\n const { deferredPromise } = Route.useLoaderData()\n\n const data = useAwaited({ promise: deferredPromise })\n\n // or\n\n return (\n <Await promise={deferredPromise}>\n {(data) => <div>{JSON.stringify(data)}</div>}\n </Await>\n )\n}\n```\n\n# ErrorComponent component\n\nThe `ErrorComponent` component is a component that renders an error message and optionally the error's message.\n\n## ErrorComponent props\n\nThe `ErrorComponent` component accepts the following props:\n\n### `props.error` prop\n\n- Type: `TError` (defaults to `Error`)\n- The error that was thrown by the component's children\n\n### `props.info` prop\n\n- Type: `{ componentStack: string }`\n- Optional\n- Additional information about where the error was thrown, such as the React component stack trace.\n\n### `props.reset` prop\n\n- Type: `() => void`\n- A function to programmatically reset the error state\n\n## ErrorComponent returns\n\n- Returns a formatted error message with the error's message if it exists.\n- The error message can be toggled by clicking the \"Show Error\" button.\n- By default, the error message will be shown in development.\n\n# getRouteApi function\n\nThe `getRouteApi` function provides type-safe version of common hooks like `useParams`, `useSearch`, `useRouteContext`, `useNavigate`, `useLoaderData`, and `useLoaderDeps` that are pre-bound to a specific route ID and corresponding registered route types.\n\n## getRouteApi options\n\nThe `getRouteApi` function accepts a single argument, a `routeId` string literal.\n\n### `routeId` option\n\n- Type: `string`\n- Required\n- The route ID to which the [`RouteApi`](../RouteApiClass.md) instance will be bound\n\n## getRouteApi returns\n\n- An instance of the [`RouteApi`](../RouteApiType.md) that is pre-bound to the route ID that the `getRouteApi` function was called with.\n\n## Examples\n\n```tsx\nimport { getRouteApi } from '@tanstack/react-router'\n\nconst routeApi = getRouteApi('/posts')\n\nexport function PostsPage() {\n const posts = routeApi.useLoaderData()\n // ...\n}\n```\n\n# HistoryState interface\n\nThe `HistoryState` interface is an interface exported by the `history` package that describes the shape of the state object that can be used in conjunction with the `history` package and the `window.location` API.\n\nYou can extend this interface to add additional properties to the state object across your application.\n\n```tsx\n// src/main.tsx\ndeclare module '@tanstack/react-router' {\n // ...\n\n interface HistoryState {\n additionalRequiredProperty: number\n additionalProperty?: string\n }\n}\n```\n\n# isNotFound function\n\nThe `isNotFound` function can be used to determine if an object is a [`NotFoundError`](../NotFoundErrorType.md) object.\n\n## isNotFound options\n\nThe `isNotFound` function accepts a single argument, an `input`.\n\n### `input` option\n\n- Type: `unknown`\n- Required\n- An object to check if it is a [`NotFoundError`](../NotFoundErrorType.md).\n\n## isNotFound returns\n\n- Type: `boolean`\n- `true` if the object is a [`NotFoundError`](../NotFoundErrorType.md).\n- `false` if the object is not a [`NotFoundError`](../NotFoundErrorType.md).\n\n## Examples\n\n```tsx\nimport { isNotFound } from '@tanstack/react-router'\n\nfunction somewhere(obj: unknown) {\n if (isNotFound(obj)) {\n // ...\n }\n}\n```\n\n# isRedirect function\n\nThe `isRedirect` function can be used to determine if an object is a redirect object.\n\n## isRedirect options\n\nThe `isRedirect` function accepts a single argument, an `input`.\n\n#### `input`\n\n- Type: `unknown`\n- Required\n- An object to check if it is a redirect object\n\n## isRedirect returns\n\n- Type: `boolean`\n- `true` if the object is a redirect object\n- `false` if the object is not a redirect object\n\n## Examples\n\n```tsx\nimport { isRedirect } from '@tanstack/react-router'\n\nfunction somewhere(obj: unknown) {\n if (isRedirect(obj)) {\n // ...\n }\n}\n```\n\n# lazyRouteComponent function\n\n> [!IMPORTANT]\n> If you are using file-based routing, it's recommended to use the `createLazyFileRoute` function instead.\n\nThe `lazyRouteComponent` function can be used to create a one-off code-split route component that can be preloaded using a `component.preload()` method.\n\n## lazyRouteComponent options\n\nThe `lazyRouteComponent` function accepts two arguments:\n\n### `importer` option\n\n- Type: `() => Promise<T>`\n- Required\n- A function that returns a promise that resolves to an object that contains the component to be loaded.\n\n### `exportName` option\n\n- Type: `string`\n- Optional\n- The name of the component to be loaded from the imported object. Defaults to `'default'`.\n\n## lazyRouteComponent returns\n\n- A `React.lazy` component that can be preloaded using a `component.preload()` method.\n\n## Examples\n\n```tsx\nimport { lazyRouteComponent } from '@tanstack/react-router'\n\nconst route = createRoute({\n path: '/posts/$postId',\n component: lazyRouteComponent(() => import('./Post')), // default export\n})\n\n// or\n\nconst route = createRoute({\n path: '/posts/$postId',\n component: lazyRouteComponent(\n () => import('./Post'),\n 'PostByIdPageComponent', // named export\n ),\n})\n```\n\n# Link component\n\nThe `Link` component is a component that can be used to create a link that can be used to navigate to a new location. This includes changes to the pathname, search params, hash, and location state.\n\n## Link props\n\nThe `Link` component accepts the following props:\n\n### `...props`\n\n- Type: `LinkProps & React.RefAttributes<HTMLAnchorElement>`\n- [`LinkProps`](../LinkPropsType.md)\n\n## Link returns\n\nAn anchor element that can be used to navigate to a new location.\n\n## Examples\n\n```tsx\nimport { Link } from '@tanstack/react-router'\n\nfunction Component() {\n return (\n <Link\n to=\"/somewhere/$somewhereId\"\n params={{ somewhereId: 'baz' }}\n search={(prev) => ({ ...prev, foo: 'bar' })}\n >\n Click me\n </Link>\n )\n}\n```\n\n# Link options\n\n`linkOptions` is a function which type checks an object literal with the intention of being used for `Link`, `navigate` or `redirect`\n\n## linkOptions props\n\nThe `linkOptions` accepts the following option:\n\n### `...props`\n\n- Type: `LinkProps & React.RefAttributes<HTMLAnchorElement>`\n- [`LinkProps`](../LinkPropsType.md)\n\n## `linkOptions` returns\n\nAn object literal with the exact type inferred from the input\n\n## Examples\n\n```tsx\nconst userLinkOptions = linkOptions({\n to: '/dashboard/users/user',\n search: {\n usersView: {\n sortBy: 'email',\n filterBy: 'filter',\n },\n userId: 0,\n },\n})\n\nfunction DashboardComponent() {\n return <Link {...userLinkOptions} />\n}\n```\n\n# MatchRoute component\n\nA component version of the `useMatchRoute` hook. It accepts the same options as the `useMatchRoute` with additional props to aid in conditional rendering.\n\n## MatchRoute props\n\nThe `MatchRoute` component accepts the same options as the `useMatchRoute` hook with additional props to aid in conditional rendering.\n\n### `...props` prop\n\n- Type: [`UseMatchRouteOptions`](../UseMatchRouteOptionsType.md)\n\n### `children` prop\n\n- Optional\n- `React.ReactNode`\n - The component that will be rendered if the route is matched.\n- `((params: TParams | false) => React.ReactNode)`\n - A function that will be called with the matched route's params or `false` if no route was matched. This can be useful for components that need to always render, but render different props based on a route match or not.\n\n## MatchRoute returns\n\nEither the `children` prop or the return value of the `children` function.\n\n## Examples\n\n```tsx\nimport { MatchRoute } from '@tanstack/react-router'\n\nfunction Component() {\n return (\n <div>\n <MatchRoute to=\"/posts/$postId\" params={{ postId: '123' }} pending>\n {(match) => <Spinner show={!!match} wait=\"delay-50\" />}\n </MatchRoute>\n </div>\n )\n}\n```\n\n# Navigate component\n\nThe `Navigate` component is a component that can be used to navigate to a new location when rendered. This includes changes to the pathname, search params, hash, and location state. The underlying navigation will happen inside of a `useEffect` hook when successfully rendered.\n\n## Navigate props\n\nThe `Navigate` component accepts the following props:\n\n### `...options`\n\n- Type: [`NavigateOptions`](../NavigateOptionsType.md)\n\n## Navigate returns\n\n- `null`\n\n# notFound function\n\nThe `notFound` function returns a new `NotFoundError` object that can be either returned or thrown from places like a Route's `beforeLoad` or `loader` callbacks to trigger the `notFoundComponent`.\n\n## notFound options\n\nThe `notFound` function accepts a single optional argument, the `options` to create the not-found error object.\n\n- Type: [`Partial<NotFoundError>`](../NotFoundErrorType.md)\n- Optional\n\n## notFound returns\n\n- If the `throw` property is `true` in the `options` object, the `NotFoundError` object will be thrown from within the function call.\n- If the `throw` property is `false | undefined` in the `options` object, the `NotFoundError` object will be returned.\n\n## Examples\n\n```tsx\nimport { notFound, createFileRoute, rootRouteId } from '@tanstack/react-router'\n\nconst Route = new createFileRoute('/posts/$postId')({\n // throwing a not-found object\n loader: ({ context: { post } }) => {\n if (!post) {\n throw notFound()\n }\n },\n // or if you want to show a not-found on the whole page\n loader: ({ context: { team } }) => {\n if (!team) {\n throw notFound({ routeId: rootRouteId })\n }\n },\n // ... other route options\n})\n```\n\n# Outlet component\n\nThe `Outlet` component is a component that can be used to render the next child route of a parent route.\n\n## Outlet props\n\nThe `Outlet` component does not accept any props.\n\n## Outlet returns\n\n- If matched, the child route match's `component`/`errorComponent`/`pendingComponent`/`notFoundComponent`.\n- If not matched, `null`.\n\n# redirect function\n\nThe `redirect` function returns a new `Redirect` object that can be either returned or thrown from places like a Route's `beforeLoad` or `loader` callbacks to trigger _redirect_ to a new location.\n\n## redirect options\n\nThe `redirect` function accepts a single argument, the `options` to determine the redirect behavior.\n\n- Type: [`Redirect`](../RedirectType.md)\n- Required\n\n## redirect returns\n\n- If the `throw` property is `true` in the `options` object, the `Redirect` object will be thrown from within the function call.\n- If the `throw` property is `false | undefined` in the `options` object, the `Redirect` object will be returned.\n\n## Examples\n\n```tsx\nimport { redirect } from '@tanstack/react-router'\n\nconst route = createRoute({\n // throwing an internal redirect object using 'to' property\n loader: () => {\n if (!user) {\n throw redirect({\n to: '/login',\n })\n }\n },\n // throwing an external redirect object using 'href' property\n loader: () => {\n if (needsExternalAuth) {\n throw redirect({\n href: 'https://authprovider.com/login',\n })\n }\n },\n // or forcing `redirect` to throw itself\n loader: () => {\n if (!user) {\n redirect({\n to: '/login',\n throw: true,\n })\n }\n },\n // ... other route options\n})\n```\n\n# Search middleware to retain search params\n\n`retainSearchParams` is a search middleware that allows to keep search params.\n\n## retainSearchParams props\n\nThe `retainSearchParams` either accepts `true` or a list of keys of those search params that shall be retained.\nIf `true` is passed in, all search params will be retained.\n\n## Examples\n\n```tsx\nimport { z } from 'zod'\nimport { createRootRoute, retainSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst searchSchema = z.object({\n rootValue: z.string().optional(),\n})\n\nexport const Route = createRootRoute({\n validateSearch: zodValidator(searchSchema),\n search: {\n middlewares: [retainSearchParams(['rootValue'])],\n },\n})\n```\n\n```tsx\nimport { z } from 'zod'\nimport { createFileRoute, retainSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst searchSchema = z.object({\n one: z.string().optional(),\n two: z.string().optional(),\n})\n\nexport const Route = createFileRoute('/')({\n validateSearch: zodValidator(searchSchema),\n search: {\n middlewares: [retainSearchParams(true)],\n },\n})\n```\n\n# rootRouteWithContext function\n\n> [!CAUTION]\n> This function is deprecated and will be removed in the next major version of TanStack Router.\n> Please use the [`createRootRouteWithContext`](../createRootRouteWithContextFunction.md) function instead.\n\nThe `rootRouteWithContext` function is a helper function that can be used to create a root route instance that requires a context type to be fulfilled when the router is created.\n\n## rootRouteWithContext generics\n\nThe `rootRouteWithContext` function accepts a single generic argument:\n\n### `TRouterContext` generic\n\n- Type: `TRouterContext`\n- Optional, **but recommended**.\n- The context type that will be required to be fulfilled when the router is created\n\n## rootRouteWithContext returns\n\n- A factory function that can be used to create a new [`createRootRoute`](../createRootRouteFunction.md) instance.\n- It accepts a single argument, the same as the [`createRootRoute`](../createRootRouteFunction.md) function.\n\n## Examples\n\n```tsx\nimport { rootRouteWithContext, createRouter } from '@tanstack/react-router'\nimport { QueryClient } from '@tanstack/react-query'\n\ninterface MyRouterContext {\n queryClient: QueryClient\n}\n\nconst rootRoute = rootRouteWithContext<MyRouterContext>()({\n component: () => <Outlet />,\n // ... root route options\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst queryClient = new QueryClient()\n\nconst router = createRouter({\n routeTree,\n context: {\n queryClient,\n },\n})\n```\n\n# Search middleware to strip search params\n\n`stripSearchParams` is a search middleware that allows to remove search params.\n\n## stripSearchParams props\n\n`stripSearchParams` accepts one of the following inputs:\n\n- `true`: if the search schema has no required params, `true` can be used to strip all search params\n- a list of keys of those search params that shall be removed; only keys of optional search params are allowed.\n- an object that conforms to the partial input search schema. The search params are compared against the values of this object; if the value is deeply equal, it will be removed. This is especially useful to strip out default search params.\n\n## Examples\n\n```tsx\nimport { z } from 'zod'\nimport { createFileRoute, stripSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst defaultValues = {\n one: 'abc',\n two: 'xyz',\n}\n\nconst searchSchema = z.object({\n one: z.string().default(defaultValues.one),\n two: z.string().default(defaultValues.two),\n})\n\nexport const Route = createFileRoute('/')({\n validateSearch: zodValidator(searchSchema),\n search: {\n // strip default values\n middlewares: [stripSearchParams(defaultValues)],\n },\n})\n```\n\n```tsx\nimport { z } from 'zod'\nimport { createRootRoute, stripSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst searchSchema = z.object({\n hello: z.string().default('world'),\n requiredParam: z.string(),\n})\n\nexport const Route = createRootRoute({\n validateSearch: zodValidator(searchSchema),\n search: {\n // always remove `hello`\n middlewares: [stripSearchParams(['hello'])],\n },\n})\n```\n\n```tsx\nimport { z } from 'zod'\nimport { createFileRoute, stripSearchParams } from '@tanstack/react-router'\nimport { zodValidator } from '@tanstack/zod-adapter'\n\nconst searchSchema = z.object({\n one: z.string().default('abc'),\n two: z.string().default('xyz'),\n})\n\nexport const Route = createFileRoute('/')({\n validateSearch: zodValidator(searchSchema),\n search: {\n // remove all search params\n middlewares: [stripSearchParams(true)],\n },\n})\n```\n\n# useAwaited hook\n\nThe `useAwaited` method is a hook that suspends until the provided promise is resolved or rejected.\n\n## useAwaited options\n\nThe `useAwaited` hook accepts a single argument, an `options` object.\n\n### `options.promise` option\n\n- Type: `Promise<T>`\n- Required\n- The deferred promise to await.\n\n## useAwaited returns\n\n- Throws an error if the promise is rejected.\n- Suspends (throws a promise) if the promise is pending.\n- Returns the resolved value of a deferred promise if the promise is resolved.\n\n## Examples\n\n```tsx\nimport { useAwaited } from '@tanstack/react-router'\n\nfunction Component() {\n const { deferredPromise } = route.useLoaderData()\n\n const data = useAwaited({ promise: myDeferredPromise })\n // ...\n}\n```\n\n# useBlocker hook\n\nThe `useBlocker` method is a hook that [blocks navigation](../../../guide/navigation-blocking.md) when a condition is met.\n\n> \u26A0\uFE0F The following new `useBlocker` API is currently _experimental_.\n\n## useBlocker options\n\nThe `useBlocker` hook accepts a single _required_ argument, an option object:\n\n### `options.shouldBlockFn` option\n\n- Required\n- Type: `ShouldBlockFn`\n- This function should return a `boolean` or a `Promise<boolean>` that tells the blocker if it should block the current navigation\n- The function has the argument of type `ShouldBlockFnArgs` passed to it, which tells you information about the current and next route and the action performed\n- Think of this function as telling the router if it should block the navigation, so returning `true` mean that it should block the navigation and `false` meaning that it should be allowed\n\n```ts\ninterface ShouldBlockFnLocation<...> {\n routeId: TRouteId\n fullPath: TFullPath\n pathname: string\n params: TAllParams\n search: TFullSearchSchema\n}\n\ntype ShouldBlockFnArgs = {\n current: ShouldBlockFnLocation\n next: ShouldBlockFnLocation\n action: HistoryAction\n}\n```\n\n### `options.disabled` option\n\n- Optional - defaults to `false`\n- Type: `boolean`\n- Specifies if the blocker should be entirely disabled or not\n\n### `options.enableBeforeUnload` option\n\n- Optional - defaults to `true`\n- Type: `boolean | (() => boolean)`\n- Tell the blocker to sometimes or always block the browser `beforeUnload` event or not\n\n### `options.withResolver` option\n\n- Optional - defaults to `false`\n- Type: `boolean`\n- Specify if the resolver returned by the hook should be used or whether your `shouldBlockFn` function itself resolves the blocking\n\n### `options.blockerFn` option (\u26A0\uFE0F deprecated)\n\n- Optional\n- Type: `BlockerFn`\n- The function that returns a `boolean` or `Promise<boolean>` indicating whether to allow navigation.\n\n### `options.condition` option (\u26A0\uFE0F deprecated)\n\n- Optional - defaults to `true`\n- Type: `boolean`\n- A navigation attempt is blocked when this condition is `true`.\n\n## useBlocker returns\n\nAn object with the controls to allow manual blocking and unblocking of navigation.\n\n- `status` - A string literal that can be either `'blocked'` or `'idle'`\n- `next` - When status is `blocked`, a type narrrowable object that contains information about the next location\n- `current` - When status is `blocked`, a type narrrowable object that contains information about the current location\n- `action` - When status is `blocked`, a `HistoryAction` string that shows the action that triggered the navigation\n- `proceed` - When status is `blocked`, a function that allows navigation to continue\n- `reset` - When status is `blocked`, a function that cancels navigation (`status` will be reset to `'idle'`)\n\nor\n\n`void` when `withResolver` is `false`\n\n## Examples\n\nTwo common use cases for the `useBlocker` hook are:\n\n### Basic usage\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const [formIsDirty, setFormIsDirty] = useState(false)\n\n useBlocker({\n shouldBlockFn: () => formIsDirty,\n })\n\n // ...\n}\n```\n\n### Custom UI\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const [formIsDirty, setFormIsDirty] = useState(false)\n\n const { proceed, reset, status, next } = useBlocker({\n shouldBlockFn: () => formIsDirty,\n withResolver: true,\n })\n\n // ...\n\n return (\n <>\n {/* ... */}\n {status === 'blocked' && (\n <div>\n <p>You are navigating to {next.pathname}</p>\n <p>Are you sure you want to leave?</p>\n <button onClick={proceed}>Yes</button>\n <button onClick={reset}>No</button>\n </div>\n )}\n </>\n}\n```\n\n### Conditional blocking\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const { proceed, reset, status } = useBlocker({\n shouldBlockFn: ({ next }) => {\n return !next.pathname.includes('step/')\n },\n withResolver: true,\n })\n\n // ...\n\n return (\n <>\n {/* ... */}\n {status === 'blocked' && (\n <div>\n <p>Are you sure you want to leave?</p>\n <button onClick={proceed}>Yes</button>\n <button onClick={reset}>No</button>\n </div>\n )}\n </>\n )\n}\n```\n\n### Without resolver\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const [formIsDirty, setFormIsDirty] = useState(false)\n\n useBlocker({\n shouldBlockFn: ({ next }) => {\n if (next.pathname.includes('step/')) {\n return false\n }\n\n const shouldLeave = confirm('Are you sure you want to leave?')\n return !shouldLeave\n },\n })\n\n // ...\n}\n```\n\n### Type narrowing\n\n```tsx\nimport { useBlocker } from '@tanstack/react-router'\n\nfunction MyComponent() {\n const [formIsDirty, setFormIsDirty] = useState(false)\n\n // block going from editor-1 to /foo/123?hello=world\n const { proceed, reset, status } = useBlocker({\n shouldBlockFn: ({ current, next }) => {\n if (\n current.routeId === '/editor-1' &&\n next.fullPath === '/foo/$id' &&\n next.params.id === '123' &&\n next.search.hello === 'world'\n ) {\n return true\n }\n return false\n },\n enableBeforeUnload: false,\n withResolver: true,\n })\n\n // ...\n}\n```\n\n# useCanGoBack hook\n\nThe `useCanGoBack` hook returns a boolean representing if the router history can safely go back without exiting the application.\n\n> \u26A0\uFE0F The following new `useCanGoBack` API is currently _experimental_.\n\n## useCanGoBack returns\n\n- If the router history is not at index `0`, `true`.\n- If the router history is at index `0`, `false`.\n\n## Limitations\n\nThe router history index is reset after a navigation with [`reloadDocument`](../NavigateOptionsType.md#reloaddocument) set as `true`. This causes the router history to consider the new location as the initial one and will cause `useCanGoBack` to return `false`.\n\n## Examples\n\n### Showing a back button\n\n```tsx\nimport { useRouter, useCanGoBack } from '@tanstack/react-router'\n\nfunction Component() {\n const router = useRouter()\n const canGoBack = useCanGoBack()\n\n return (\n <div>\n {canGoBack ? (\n <button onClick={() => router.history.back()}>Go back</button>\n ) : null}\n\n {/* ... */}\n </div>\n )\n}\n```\n\n# useChildMatches hook\n\nThe `useChildMatches` hook returns all of the child [`RouteMatch`](../RouteMatchType.md) objects from the closest match down to the leaf-most match. **It does not include the current match, which can be obtained using the `useMatch` hook.**\n\n> [!IMPORTANT]\n> If the router has pending matches and they are showing their pending component fallbacks, `router.state.pendingMatches` will used instead of `router.state.matches`.\n\n## useChildMatches options\n\nThe `useChildMatches` hook accepts a single _optional_ argument, an `options` object.\n\n### `opts.select` option\n\n- Optional\n- `(matches: RouteMatch[]) => TSelected`\n- If supplied, this function will be called with the route matches and the return value will be returned from `useChildMatches`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useChildMatches returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, an array of [`RouteMatch`](../RouteMatchType.md) objects.\n\n## Examples\n\n```tsx\nimport { useChildMatches } from '@tanstack/react-router'\n\nfunction Component() {\n const childMatches = useChildMatches()\n // ...\n}\n```\n\n# useLinkProps hook\n\nThe `useLinkProps` hook that takes an object as its argument and returns a `React.AnchorHTMLAttributes<HTMLAnchorElement>` props object. These props can then be safely applied to an anchor element to create a link that can be used to navigate to the new location. This includes changes to the pathname, search params, hash, and location state.\n\n## useLinkProps options\n\n```tsx\ntype UseLinkPropsOptions = ActiveLinkOptions &\n React.AnchorHTMLAttributes<HTMLAnchorElement>\n```\n\n- [`ActiveLinkOptions`](../ActiveLinkOptionsType.md)\n- The `useLinkProps` options are used to build a [`LinkProps`](../LinkPropsType.md) object.\n- It also extends the `React.AnchorHTMLAttributes<HTMLAnchorElement>` type, so that any additional props that are passed to the `useLinkProps` hook will be merged with the [`LinkProps`](../LinkPropsType.md) object.\n\n## useLinkProps returns\n\n- A `React.AnchorHTMLAttributes<HTMLAnchorElement>` object that can be applied to an anchor element to create a link that can be used to navigate to the new location\n\n# useLoaderData hook\n\nThe `useLoaderData` hook returns the loader data from the closest [`RouteMatch`](../RouteMatchType.md) in the component tree.\n\n## useLoaderData options\n\nThe `useLoaderData` hook accepts an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- The route id of the closest parent match\n- Optional, but recommended for full type safety.\n- If `opts.strict` is `true`, TypeScript will warn for this option if it is not provided.\n- If `opts.strict` is `false`, TypeScript will provided loosened types for the returned loader data.\n\n### `opts.strict` option\n\n- Type: `boolean`\n- Optional - `default: true`\n- If `false`, the `opts.from` option will be ignored and types will be loosened to to reflect the shared types of all possible loader data.\n\n### `opts.select` option\n\n- Optional\n- `(loaderData: TLoaderData) => TSelected`\n- If supplied, this function will be called with the loader data and the return value will be returned from `useLoaderData`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useLoaderData returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, the loader data or a loosened version of the loader data if `opts.strict` is `false`.\n\n## Examples\n\n```tsx\nimport { useLoaderData } from '@tanstack/react-router'\n\nfunction Component() {\n const loaderData = useLoaderData({ from: '/posts/$postId' })\n // ^? { postId: string, body: string, ... }\n // ...\n}\n```\n\n# useLoaderDeps hook\n\nThe `useLoaderDeps` hook is a hook that returns an object with the dependencies that are used to trigger the `loader` for a given route.\n\n## useLoaderDepsHook options\n\nThe `useLoaderDepsHook` hook accepts an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- Required\n- The RouteID or path to get the loader dependencies from.\n\n### `opts.select` option\n\n- Type: `(deps: TLoaderDeps) => TSelected`\n- Optional\n- If supplied, this function will be called with the loader dependencies object and the return value will be returned from `useLoaderDeps`.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useLoaderDeps returns\n\n- An object of the loader dependencies or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useLoaderDeps } from '@tanstack/react-router'\n\nconst routeApi = getRouteApi('/posts/$postId')\n\nfunction Component() {\n const deps = useLoaderDeps({ from: '/posts/$postId' })\n\n // OR\n\n const routeDeps = routeApi.useLoaderDeps()\n\n // OR\n\n const postId = useLoaderDeps({\n from: '/posts',\n select: (deps) => deps.view,\n })\n\n // ...\n}\n```\n\n# useLocation hook\n\nThe `useLocation` method is a hook that returns the current [`location`](../ParsedLocationType.md) object. This hook is useful for when you want to perform some side effect whenever the current location changes.\n\n## useLocation options\n\nThe `useLocation` hook accepts an optional `options` object.\n\n### `opts.select` option\n\n- Type: `(state: ParsedLocationType) => TSelected`\n- Optional\n- If supplied, this function will be called with the [`location`](../ParsedLocationType.md) object and the return value will be returned from `useLocation`.\n\n## useLocation returns\n\n- The current [`location`](../ParsedLocationType.md) object or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useLocation } from '@tanstack/react-router'\n\nfunction Component() {\n const location = useLocation()\n // ^ ParsedLocation\n\n // OR\n\n const pathname = useLocation({\n select: (location) => location.pathname,\n })\n // ^ string\n\n // ...\n}\n```\n\n# useMatch hook\n\nThe `useMatch` hook returns a [`RouteMatch`](../RouteMatchType.md) in the component tree. The raw route match contains all of the information about a route match in the router and also powers many other hooks under the hood like `useParams`, `useLoaderData`, `useRouteContext`, and `useSearch`.\n\n## useMatch options\n\nThe `useMatch` hook accepts a single argument, an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- The route id of a match\n- Optional, but recommended for full type safety.\n- If `opts.strict` is `true`, `from` is required and TypeScript will warn for this option if it is not provided.\n- If `opts.strict` is `false`, `from` must not be set and TypeScript will provided loosened types for the returned [`RouteMatch`](../RouteMatchType.md).\n\n### `opts.strict` option\n\n- Type: `boolean`\n- Optional\n- `default: true`\n- If `false`, the `opts.from` must not be set and types will be loosened to `Partial<RouteMatch>` to reflect the shared types of all matches.\n\n### `opts.select` option\n\n- Optional\n- `(match: RouteMatch) => TSelected`\n- If supplied, this function will be called with the route match and the return value will be returned from `useMatch`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n### `opts.shouldThrow` option\n\n- Type: `boolean`\n- Optional\n- `default: true`\n- If `false`,`useMatch` will not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will return `undefined`.\n\n## useMatch returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, the [`RouteMatch`](../RouteMatchType.md) object or a loosened version of the `RouteMatch` object if `opts.strict` is `false`.\n\n## Examples\n\n### Accessing a route match\n\n```tsx\nimport { useMatch } from '@tanstack/react-router'\n\nfunction Component() {\n const match = useMatch({ from: '/posts/$postId' })\n // ^? strict match for RouteMatch\n // ...\n}\n```\n\n### Accessing the root route's match\n\n```tsx\nimport {\n useMatch,\n rootRouteId, // <<<< use this token!\n} from '@tanstack/react-router'\n\nfunction Component() {\n const match = useMatch({ from: rootRouteId })\n // ^? strict match for RouteMatch\n // ...\n}\n```\n\n### Checking if a specific route is currently rendered\n\n```tsx\nimport { useMatch } from '@tanstack/react-router'\n\nfunction Component() {\n const match = useMatch({ from: '/posts', shouldThrow: false })\n // ^? RouteMatch | undefined\n if (match !== undefined) {\n // ...\n }\n}\n```\n\n# useMatchRoute hook\n\nThe `useMatchRoute` hook is a hook that returns a `matchRoute` function that can be used to match a route against either the current or pending location.\n\n## useMatchRoute returns\n\n- A `matchRoute` function that can be used to match a route against either the current or pending location.\n\n## matchRoute function\n\nThe `matchRoute` function is a function that can be used to match a route against either the current or pending location.\n\n### matchRoute function options\n\nThe `matchRoute` function accepts a single argument, an `options` object.\n\n- Type: [`UseMatchRouteOptions`](../UseMatchRouteOptionsType.md)\n\n### matchRoute function returns\n\n- The matched route's params or `false` if no route was matched\n\n## Examples\n\n```tsx\nimport { useMatchRoute } from '@tanstack/react-router'\n\n// Current location: /posts/123\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts/$postId' })\n // ^ { postId: '123' }\n}\n\n// Current location: /posts/123\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts' })\n // ^ false\n}\n\n// Current location: /posts/123\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts', fuzzy: true })\n // ^ {}\n}\n\n// Current location: /posts\n// Pending location: /posts/123\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts/$postId', pending: true })\n // ^ { postId: '123' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({ to: '/posts/$postId/foo/$fooId' })\n // ^ { postId: '123', fooId: '456' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { postId: '123' },\n })\n // ^ { postId: '123', fooId: '456' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { postId: '789' },\n })\n // ^ false\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { fooId: '456' },\n })\n // ^ { postId: '123', fooId: '456' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { postId: '123', fooId: '456' },\n })\n // ^ { postId: '123', fooId: '456' }\n}\n\n// Current location: /posts/123/foo/456\nfunction Component() {\n const matchRoute = useMatchRoute()\n const params = matchRoute({\n to: '/posts/$postId/foo/$fooId',\n params: { postId: '789', fooId: '456' },\n })\n // ^ false\n}\n```\n\n# useMatches hook\n\nThe `useMatches` hook returns all of the [`RouteMatch`](../RouteMatchType.md) objects from the router **regardless of its callers position in the React component tree**.\n\n> [!TIP]\n> If you only want the parent or child matches, then you can use the [`useParentMatches`](../useParentMatchesHook.md) or the [`useChildMatches`](../useChildMatchesHook.md) based on the selection you need.\n\n## useMatches options\n\nThe `useMatches` hook accepts a single _optional_ argument, an `options` object.\n\n### `opts.select` option\n\n- Optional\n- `(matches: RouteMatch[]) => TSelected`\n- If supplied, this function will be called with the route matches and the return value will be returned from `useMatches`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useMatches returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, an array of [`RouteMatch`](../RouteMatchType.md) objects.\n\n## Examples\n\n```tsx\nimport { useMatches } from '@tanstack/react-router'\n\nfunction Component() {\n const matches = useMatches()\n // ^? [RouteMatch, RouteMatch, ...]\n // ...\n}\n```\n\n# useNavigate hook\n\nThe `useNavigate` hook is a hook that returns a `navigate` function that can be used to navigate to a new location. This includes changes to the pathname, search params, hash, and location state.\n\n## useNavigate options\n\nThe `useNavigate` hook accepts a single argument, an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- Optional\n- Description: The location to navigate from. This is useful when you want to navigate to a new location from a specific location, rather than the current location.\n\n## useNavigate returns\n\n- A `navigate` function that can be used to navigate to a new location.\n\n## navigate function\n\nThe `navigate` function is a function that can be used to navigate to a new location.\n\n### navigate function options\n\nThe `navigate` function accepts a single argument, an `options` object.\n\n- Type: [`NavigateOptions`](../NavigateOptionsType.md)\n\n### navigate function returns\n\n- A `Promise` that resolves when the navigation is complete\n\n## Examples\n\n```tsx\nimport { useNavigate } from '@tanstack/react-router'\n\nfunction PostsPage() {\n const navigate = useNavigate({ from: '/posts' })\n const handleClick = () => navigate({ search: { page: 2 } })\n // ...\n}\n\nfunction Component() {\n const navigate = useNavigate()\n return (\n <div>\n <button\n onClick={() =>\n navigate({\n to: '/posts',\n })\n }\n >\n Posts\n </button>\n <button\n onClick={() =>\n navigate({\n to: '/posts',\n search: { page: 2 },\n })\n }\n >\n Posts (Page 2)\n </button>\n <button\n onClick={() =>\n navigate({\n to: '/posts',\n hash: 'my-hash',\n })\n }\n >\n Posts (Hash)\n </button>\n <button\n onClick={() =>\n navigate({\n to: '/posts',\n state: { from: 'home' },\n })\n }\n >\n Posts (State)\n </button>\n </div>\n )\n}\n```\n\n# useParams hook\n\nThe `useParams` method returns all of the path parameters that were parsed for the closest match and all of its parent matches.\n\n## useParams options\n\nThe `useParams` hook accepts an optional `options` object.\n\n### `opts.strict` option\n\n- Type: `boolean`\n- Optional - `default: true`\n- If `false`, the `opts.from` option will be ignored and types will be loosened to `Partial<AllParams>` to reflect the shared types of all params.\n\n### `opts.shouldThrow` option\n\n- Type: `boolean`\n- Optional\n- `default: true`\n- If `false`,`useParams` will not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will return `undefined`.\n\n### `opts.select` option\n\n- Optional\n- `(params: AllParams) => TSelected`\n- If supplied, this function will be called with the params object and the return value will be returned from `useParams`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useParams returns\n\n- An object of of the match's and parent match path params or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useParams } from '@tanstack/react-router'\n\nconst routeApi = getRouteApi('/posts/$postId')\n\nfunction Component() {\n const params = useParams({ from: '/posts/$postId' })\n\n // OR\n\n const routeParams = routeApi.useParams()\n\n // OR\n\n const postId = useParams({\n from: '/posts/$postId',\n select: (params) => params.postId,\n })\n\n // OR\n\n const looseParams = useParams({ strict: false })\n\n // ...\n}\n```\n\n# useParentMatches hook\n\nThe `useParentMatches` hook returns all of the parent [`RouteMatch`](../RouteMatchType.md) objects from the root down to the immediate parent of the current match in context. **It does not include the current match, which can be obtained using the `useMatch` hook.**\n\n> [!IMPORTANT]\n> If the router has pending matches and they are showing their pending component fallbacks, `router.state.pendingMatches` will used instead of `router.state.matches`.\n\n## useParentMatches options\n\nThe `useParentMatches` hook accepts an optional `options` object.\n\n### `opts.select` option\n\n- Optional\n- `(matches: RouteMatch[]) => TSelected`\n- If supplied, this function will be called with the route matches and the return value will be returned from `useParentMatches`. This value will also be used to determine if the hook should re-render its parent component using shallow equality checks.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useParentMatches returns\n\n- If a `select` function is provided, the return value of the `select` function.\n- If no `select` function is provided, an array of [`RouteMatch`](../RouteMatchType.md) objects.\n\n## Examples\n\n```tsx\nimport { useParentMatches } from '@tanstack/react-router'\n\nfunction Component() {\n const parentMatches = useParentMatches()\n // ^ [RouteMatch, RouteMatch, ...]\n}\n```\n\n# useRouteContext hook\n\nThe `useRouteContext` method is a hook that returns the current context for the current route. This hook is useful for accessing the current route context in a component.\n\n## useRouteContext options\n\nThe `useRouteContext` hook accepts an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- Required\n- The RouteID to match the route context from.\n\n### `opts.select` option\n\n- Type: `(context: RouteContext) => TSelected`\n- Optional\n- If supplied, this function will be called with the route context object and the return value will be returned from `useRouteContext`.\n\n## useRouteContext returns\n\n- The current context for the current route or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useRouteContext } from '@tanstack/react-router'\n\nfunction Component() {\n const context = useRouteContext({ from: '/posts/$postId' })\n // ^ RouteContext\n\n // OR\n\n const selected = useRouteContext({\n from: '/posts/$postId',\n select: (context) => context.postId,\n })\n // ^ string\n\n // ...\n}\n```\n\n# useRouter hook\n\nThe `useRouter` method is a hook that returns the current instance of [`Router`](../RouterType.md) from context. This hook is useful for accessing the router instance in a component.\n\n## useRouter returns\n\n- The current [`Router`](../RouterType.md) instance.\n\n> \u26A0\uFE0F\u26A0\uFE0F\u26A0\uFE0F **`router.state` is always up to date, but NOT REACTIVE. If you use `router.state` in a component, the component will not re-render when the router state changes. To get a reactive version of the router state, use the [`useRouterState`](../useRouterStateHook.md) hook.**\n\n## Examples\n\n```tsx\nimport { useRouter } from '@tanstack/react-router'\n\nfunction Component() {\n const router = useRouter()\n // ^ Router\n\n // ...\n}\n```\n\n# useRouterState hook\n\nThe `useRouterState` method is a hook that returns the current internal state of the router. This hook is useful for accessing the current state of the router in a component.\n\n> [!TIP]\n> If you want to access the current location or the current matches, you should try out the [`useLocation`](../useLocationHook.md) and [`useMatches`](../useMatchesHook.md) hooks first. These hooks are designed to be more ergonomic and easier to use than accessing the router state directly.\n\n## useRouterState options\n\nThe `useRouterState` hook accepts an optional `options` object.\n\n### `opts.select` option\n\n- Type: `(state: RouterState) => TSelected`\n- Optional\n- If supplied, this function will be called with the [`RouterState`](../RouterStateType.md) object and the return value will be returned from `useRouterState`.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n## useRouterState returns\n\n- The current [`RouterState`](../RouterStateType.md) object or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useRouterState } from '@tanstack/react-router'\n\nfunction Component() {\n const state = useRouterState()\n // ^ RouterState\n\n // OR\n\n const selected = useRouterState({\n select: (state) => state.location,\n })\n // ^ ParsedLocation\n\n // ...\n}\n```\n\n# useSearch hook\n\nThe `useSearch` method is a hook that returns the current search query parameters as an object for the current location. This hook is useful for accessing the current search string and query parameters in a component.\n\n## useSearch options\n\nThe `useSearch` hook accepts an `options` object.\n\n### `opts.from` option\n\n- Type: `string`\n- Required\n- The RouteID to match the search query parameters from.\n\n### `opts.shouldThrow` option\n\n- Type: `boolean`\n- Optional\n- `default: true`\n- If `false`,`useSearch` will not throw an invariant exception in case a match was not found in the currently rendered matches; in this case, it will return `undefined`.\n\n### `opts.select` option\n\n- Type: `(search: SelectedSearchSchema) => TSelected`\n- Optional\n- If supplied, this function will be called with the search object and the return value will be returned from `useSearch`.\n\n### `opts.structuralSharing` option\n\n- Type: `boolean`\n- Optional\n- Configures whether structural sharing is enabled for the value returned by `select`.\n- See the [Render Optimizations guide](../../../guide/render-optimizations.md) for more information.\n\n### `opts.strict` option\n\n- Type: `boolean`\n- Optional - `default: true`\n- If `false`, the `opts.from` option will be ignored and types will be loosened to `Partial<FullSearchSchema>` to reflect the shared types of all search query parameters.\n\n## useSearch returns\n\n- If `opts.from` is provided, an object of the search query parameters for the current location or `TSelected` if a `select` function is provided.\n- If `opts.strict` is `false`, an object of the search query parameters for the current location or `TSelected` if a `select` function is provided.\n\n## Examples\n\n```tsx\nimport { useSearch } from '@tanstack/react-router'\n\nfunction Component() {\n const search = useSearch({ from: '/posts/$postId' })\n // ^ FullSearchSchema\n\n // OR\n\n const selected = useSearch({\n from: '/posts/$postId',\n select: (search) => search.postView,\n })\n // ^ string\n\n // OR\n\n const looseSearch = useSearch({ strict: false })\n // ^ Partial<FullSearchSchema>\n\n // ...\n}\n```\n\n";
|
|
2
2
|
export default _default;
|
package/dist/llms/rules/api.js
CHANGED
|
@@ -263,7 +263,7 @@ The \`NavigateOptions\` object accepts the following properties:
|
|
|
263
263
|
- Optional
|
|
264
264
|
- Defaults to \`false\`.
|
|
265
265
|
- If \`true\`, navigation will be called using \`document.startViewTransition()\`.
|
|
266
|
-
- If [\`ViewTransitionOptions\`](../ViewTransitionOptionsType.md), route navigations will be called using \`document.startViewTransition({update, types})\` where \`types\` will
|
|
266
|
+
- If [\`ViewTransitionOptions\`](../ViewTransitionOptionsType.md), route navigations will be called using \`document.startViewTransition({update, types})\` where \`types\` will determine the strings array passed with \`ViewTransitionOptions["types"]\`. If the browser does not support viewTransition types, the navigation will fall back to normal \`document.startTransition()\`, same as if \`true\` was passed.
|
|
267
267
|
- If the browser does not support this api, this option will be ignored.
|
|
268
268
|
- See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Document/startViewTransition) for more information on how this function works.
|
|
269
269
|
- See [Google](https://developer.chrome.com/docs/web-platform/view-transitions/same-document#view-transition-types) for more information on viewTransition types
|
|
@@ -2003,7 +2003,15 @@ The \`ViewTransitionOptions\` type is used to define a
|
|
|
2003
2003
|
|
|
2004
2004
|
\`\`\`tsx
|
|
2005
2005
|
interface ViewTransitionOptions {
|
|
2006
|
-
types:
|
|
2006
|
+
types:
|
|
2007
|
+
| Array<string>
|
|
2008
|
+
| ((locationChangeInfo: {
|
|
2009
|
+
fromLocation?: ParsedLocation
|
|
2010
|
+
toLocation: ParsedLocation
|
|
2011
|
+
pathChanged: boolean
|
|
2012
|
+
hrefChanged: boolean
|
|
2013
|
+
hashChanged: boolean
|
|
2014
|
+
}) => Array<string> | false)
|
|
2007
2015
|
}
|
|
2008
2016
|
\`\`\`
|
|
2009
2017
|
|
|
@@ -2013,9 +2021,19 @@ The \`ViewTransitionOptions\` type accepts an object with a single property:
|
|
|
2013
2021
|
|
|
2014
2022
|
### \`types\` property
|
|
2015
2023
|
|
|
2016
|
-
- Type: \`Array<string
|
|
2024
|
+
- Type: \`Array<string> | ((locationChangeInfo: {
|
|
2025
|
+
fromLocation?: ParsedLocation
|
|
2026
|
+
toLocation: ParsedLocation
|
|
2027
|
+
pathChanged: boolean
|
|
2028
|
+
hrefChanged: boolean
|
|
2029
|
+
hashChanged: boolean
|
|
2030
|
+
}) => (Array<string> | false))\`
|
|
2017
2031
|
- Required
|
|
2018
|
-
-
|
|
2032
|
+
- Either one of:
|
|
2033
|
+
- An array of strings that will be passed to the \`document.startViewTransition({update, types}) call\`
|
|
2034
|
+
- A function that accepts \`locationChangeInfo\` object and returns either:
|
|
2035
|
+
- An array of strings that will be passed to the \`document.startViewTransition({update, types}) call\`
|
|
2036
|
+
- or \`false\` to skip the view transition
|
|
2019
2037
|
|
|
2020
2038
|
# Await component
|
|
2021
2039
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
declare const _default: "# Overview\n\n**TanStack Router is a router for building React and Solid applications**. Some of its features include:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Nested Routing and layout routes (with pathless layouts)\n- Built-in Route Loaders w/ SWR Caching\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Automatic route prefetching\n- Asynchronous route elements and error boundaries\n- File-based Route Generation\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Param Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Route matching/loading middleware\n\nTo get started quickly, head to the next page. For a more lengthy explanation, buckle up while I bring you up to speed!\n\n## \"A Fork in the Route\"\n\nUsing a router to build applications is widely regarded as a must-have and is usually one of the first choices you\u2019ll make in your tech stack.\n\n[//]: # 'WhyChooseTanStackRouter'\n\n**So, why should you choose TanStack Router over another router?**\n\nTo answer this question, we need to look at the other options in the space. There are many if you look hard enough, but in my experience, only a couple are worth exploring seriously:\n\n- **Next.js** - Widely regarded as the de facto framework for starting a new React project, it\u2019s laser focused on performance, workflow, and bleeding edge technology. Its APIs and abstractions are powerful, but can sometimes come across as non-standard. Its extremely fast growth and adoption in the industry has resulted in a featured packed experience, but at the expense of feeling overwhelming and sometimes bloated.\n- **Remix / React Router** - A full-stack framework based on the historically successful React Router offers a similarly powerful developer and user experience, with APIs and vision based firmly on web standards like Request/Response and a focus on running anywhere JS can run. Many of its APIs and abstractions are wonderfully designed and were inspiration for more than a few TanStack Router APIs. That said, its rigid design, bolted-on type safety and sometimes strict over-adherence to platform APIs can leave some developers wanting more.\n\nBoth of these frameworks (and their routers) are great, and I can personally attest that both are very good solutions for building React applications. My experience has also taught me that these solutions could also be much better, especially around the actual routing APIs that are available to developers to make their apps faster, easier, and more enjoyable to work with.\n\nIt's probably no surprise at this point that picking a router is so important that it is often tied 1-to-1 with your choice of framework, since most frameworks rely on a specific router.\n\n[//]: # 'WhyChooseTanStackRouter'\n\n**Does this mean that TanStack Router is a framework?**\n\nTanStack Router itself is not a \"framework\" in the traditional sense, since it doesn't address a few other common full-stack concerns. However TanStack Router has been designed to be upgradable to a full-stack framework when used in conjunction with other tools that address bundling, deployments, and server-side-specific functionality. This is why we are currently developing [TanStack Start](https://tanstack.com/start), a full-stack framework that is built on top of TanStack Router and Vite.\n\nFor a deeper dive on the history of TanStack Router, feel free to read [TanStack Router's History](../decisions-on-dx.md#tanstack-routers-origin-story).\n\n## Why TanStack Router?\n\nTanStack Router delivers on the same fundamental expectations as other routers that you\u2019ve come to expect:\n\n- Nested routes, layout routes, grouped routes\n- File-based Routing\n- Parallel data loading\n- Prefetching\n- URL Path Params\n- Error Boundaries and Handling\n- SSR\n- Route Masking\n\nAnd it also delivers some new features that raise the bar:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Built-in SWR Caching for loaders\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Parameter Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Inherited Route Context\n- Mixed file-based and code-based routing\n\nLet\u2019s dive into some of the more important ones in more detail!\n\n## 100% Inferred TypeScript Support\n\nEverything these days is written \u201Cin Typescript\u201D or at the very least offers type definitions that are veneered over runtime functionality, but too few packages in the ecosystem actually design their APIs with TypeScript in mind. So while I\u2019m pleased that your router is auto-completing your option fields and catching a few property/method typos here and there, there is much more to be had.\n\n- TanStack Router is fully aware of all of your routes and their configuration at any given point in your code. This includes the path, path params, search params, context, and any other configuration you\u2019ve provided. Ultimately this means that you can navigate to any route in your app with 100% type safety and confidence that your link or navigate call will succeed.\n- TanStack Router provides lossless type-inference. It uses countless generic type parameters to enforce and propagate any type information you give it throughout the rest of its API and ultimately your app. No other router offers this level of type safety and developer confidence.\n\nWhat does all of that mean for you?\n\n- Faster feature development with auto-completion and type hints\n- Safer and faster refactors\n- Confidence that your code will work as expected\n\n## 1st Class Search Parameters\n\nSearch parameters are often an afterthought, treated like a black box of strings (or string) that you can parse and update, but not much else. Existing solutions are **not** type-safe either, adding to the caution that is required to deal with them. Even the most \"modern\" frameworks and routers leave it up to you to figure out how to manage this state. Sometimes they'll parse the search string into an object for you, or sometimes you're left to do it yourself with `URLSearchParams`.\n\nLet's step back and remember that **search params are the most powerful state manager in your entire application.** They are global, serializable, bookmarkable, and shareable making them the perfect place to store any kind of state that needs to survive a page refresh or a social share.\n\nTo live up to that responsibility, search parameters are a first-class citizen in TanStack Router. While still based on standard URLSearchParams, TanStack Router uses a powerful parser/serializer to manage deeper and more complex data structures in your search params, all while keeping them type-safe and easy to work with.\n\n**It's like having `useState` right in the URL!**\n\nSearch parameters are:\n\n- Automatically parsed and serialized as JSON\n- Validated and typed\n- Inherited from parent routes\n- Accessible in loaders, components, and hooks\n- Easily modified with the useSearch hook, Link, navigate, and router.navigate APIs\n- Customizable with a custom search filters and middleware\n- Subscribed via fine-grained search param selectors for efficient re-renders\n\nOnce you start using TanStack Router's search parameters, you'll wonder how you ever lived without them.\n\n## Built-In Caching and Friendly Data Loading\n\nData loading is a critical part of any application and while most existing routers offer some form of critical data loading APIs, they often fall short when it comes to caching and data lifecycle management. Existing solutions suffer from a few common problems:\n\n- No caching at all. Data is always fresh, but your users are left waiting for frequently accessed data to load over and over again.\n- Overly-aggressive caching. Data is cached for too long, leading to stale data and a poor user experience.\n- Blunt invalidation strategies and APIs. Data may be invalidated too often, leading to unnecessary network requests and wasted resources, or you may not have any fine-grained control over when data is invalidated at all.\n\nTanStack Router solves these problems with a two-prong approach to caching and data loading:\n\n### Built-in Cache\n\nTanStack Router provides a light-weight built-in caching layer that works seamlessly with the Router. This caching layer is loosely based on TanStack Query, but with fewer features and a much smaller API surface area. Like TanStack Query, sane but powerful defaults guarantee that your data is cached for reuse, invalidated when necessary, and garbage collected when not in use. It also provides a simple API for invalidating the cache manually when needed.\n\n### Flexible & Powerful Data Lifecycle APIs\n\nTanStack Router is designed with a flexible and powerful data loading API that more easily integrates with existing data fetching libraries like TanStack Query, SWR, Apollo, Relay, or even your own custom data fetching solution. Configurable APIs like `context`, `beforeLoad`, `loaderDeps` and `loader` work in unison to make it easy to define declarative data dependencies, prefetch data, and manage the lifecycle of an external data source with ease.\n\n## Inherited Route Context\n\nTanStack Router's router and route context is a powerful feature that allows you to define context that is specific to a route which is then inherited by all child routes. Even the router and root routes themselves can provide context. Context can be built up both synchronously and asynchronously, and can be used to share data, configuration, or even functions between routes and route configurations. This is especially useful for scenarios like:\n\n- Authentication and Authorization\n- Hybrid SSR/CSR data fetching and preloading\n- Theming\n- Singletons and global utilities\n- Curried or partial application across preloading, loading, and rendering stages\n\nAlso, what would route context be if it weren't type-safe? TanStack Router's route context is fully type-safe and inferred at zero cost to you.\n\n## File-based and/or Code-Based Routing\n\nTanStack Router supports both file-based and code-based routing at the same time. This flexibility allows you to choose the approach that best fits your project's needs.\n\nTanStack Router's file-based routing approach is uniquely user-facing. Route configuration is generated for you either by the Vite plugin or TanStack Router CLI, leaving the usage of said generated code up to you! This means that you're always in total control of your routes and router, even if you use file-based routing.\n\n## Acknowledgements\n\nTanStack Router builds on concepts and patterns popularized by many other OSS projects, including:\n\n- [TRPC](https://trpc.io/)\n- [Remix](https://remix.run)\n- [Chicane](https://swan-io.github.io/chicane/)\n- [Next.js](https://nextjs.org)\n\nWe acknowledge the investment, risk and research that went into their development, but are excited to push the bar they have set even higher.\n\n## Let's go!\n\nEnough overview, there's so much more to do with TanStack Router. Hit that next button and let's get started!\n\n# Quick Start\n\nTanStack Router can be quickly added to any existing React project or used to scaffold a new one.\n\n## TanStack Router Installation\n\n### Requirements\n\nBefore installing TanStack router, please ensure your project meets the following requirements:\n\n[//]: # 'Requirements'\n\n- `react` v18 or later with `createRoot` support.\n- `react-dom` v18 or later.\n\n[//]: # 'Requirements'\n\n> [!NOTE] Using TypeScript (`v5.3.x or higher`) is recommended for the best development experience, though not strictly required. We aim to support the last 5 minor versions of TypeScript, but using the latest version will help avoid potential issues.\n\nTanStack Router is currently only compatible with React (with ReactDOM) and Solid. If you're interested in contributing to support other frameworks, such as React Native, Angular, or Vue, please reach out to us on [Discord](https://tlinz.com/discord).\n\n### Download and Install\n\nTo install TanStack Router in your project, run the following command using your preferred package manager:\n\n[//]: # 'installCommand'\n\n```sh\nnpm install @tanstack/react-router\n# or\npnpm add @tanstack/react-router\n#or\nyarn add @tanstack/react-router\n# or\nbun add @tanstack/react-router\n# or\ndeno add npm:@tanstack/react-router\n```\n\n[//]: # 'installCommand'\n\nOnce installed, you can verify the installation by checking your `package.json` file for the dependency.\n\n[//]: # 'packageJson'\n\n```json\n{\n \"dependencies\": {\n \"@tanstack/react-router\": \"^x.x.x\"\n }\n}\n```\n\n[//]: # 'packageJson'\n\n## New Project Setup\n\nTo quickly scaffold a new project with TanStack Router, you can use the `create-tsrouter-app` command-line tool. This tool sets up a new React application with TanStack Router pre-configured, allowing you to get started quickly.\n\n> [!TIP] For full details on available options and templates, visit the [`create-tsrouter-app` documentation](https://github.com/TanStack/create-tsrouter-app/tree/main/cli/create-tsrouter-app).\n\nTo create a new project, run the following command in your terminal:\n\n[//]: # 'createAppCommand'\n\n```sh\nnpx create-tsrouter-app@latest\n```\n\n[//]: # 'createAppCommand'\n\nThe CLI will guide you through a short series of prompts to customize your setup, including options for:\n\n[//]: # 'CLIPrompts'\n\n- File-based or code-based route configuration\n- TypeScript support\n- Tailwind CSS integration\n- Toolchain setup\n- Git initialization\n\n[//]: # 'CLIPrompts'\n\nOnce complete, a new React project will be generated with TanStack Router installed and ready to use. All dependencies are automatically installed, so you can jump straight into development:\n\n```sh\ncd your-project-name\nnpm run dev\n```\n\n### Routing Options\n\nTanStack Router supports both file-based and code-based route configurations, allowing you to choose the approach that best fits your workflow.\n\n#### File-Based Route Generation\n\nThe file-based approach is the recommended option for most projects. It automatically creates routes based on your file structure, giving you the best mix of performance, simplicity, and developer experience.\n\nTo create a new project using file-based route generation, run the following command:\n\n[//]: # 'createAppCommandFileBased'\n\n```sh\nnpx create-tsrouter-app@latest my-app --template file-router\n```\n\n[//]: # 'createAppCommandFileBased'\n\nThis command sets up a new directory called `my-app` with everything configured. Once setup completes, you can then start your development server and begin building your application:\n\n```sh\ncd my-app\nnpm run dev\n```\n\n#### Code-Based Route Configuration\n\nIf you prefer to define routes programmatically, you can use the code-based route configuration. This approach gives you full control over routing logic while maintaining the same project scaffolding workflow.\n\n[//]: # 'createAppCommandCodeBased'\n\n```sh\nnpx create-tsrouter-app@latest my-app\n```\n\n[//]: # 'createAppCommandCodeBased'\n\nSimilar to the file-based setup, this command creates a new directory called `my-app` with TanStack Router configured for code-based routing. After setup, navigate to your project directory and start the development server:\n\n```sh\ncd my-app\nnpm run dev\n```\n\nWith either approach, you can now start building your React application with TanStack Router!\n\n# Decisions on Developer Experience\n\nWhen people first start using TanStack Router, they often have a lot of questions that revolve around the following themes:\n\n> Why do I have to do things this way?\n\n> Why is it done this way? and not that way?\n\n> I'm used to doing it this way, why should I change?\n\nAnd they are all valid questions. For the most part, people are used to using routing libraries that are very similar to each other. They all have a similar API, similar concepts, and similar ways of doing things.\n\nBut TanStack Router is different. It's not your average routing library. It's not your average state management library. It's not your average anything.\n\n## TanStack Router's origin story\n\nIt's important to remember that TanStack Router's origins stem from [Nozzle.io](https://nozzle.io)'s need for a client-side routing solution that offered a first-in-class _URL Search Parameters_ experience without compromising on the **_type-safety_** that was required to power its complex dashboards.\n\nAnd so, from TanStack Router's very inception, every facet of its design was meticulously thought out to ensure that its type-safety and developer experience were second to none.\n\n## How does TanStack Router achieve this?\n\n> TypeScript! TypeScript! TypeScript!\n\nEvery aspect of TanStack Router is designed to be as type-safe as possible, and this is achieved by leveraging TypeScript's type system to its fullest extent. This involves using some very advanced and complex types, type inference, and other features to ensure that the developer experience is as smooth as possible.\n\nBut to achieve this, we had to make some decisions that deviate from the norms in the routing world.\n\n1. [**Route configuration boilerplate?**](#1-why-is-the-routers-configuration-done-this-way): You have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.\n2. [**TypeScript module declaration for the router?**](#2-declaring-the-router-instance-for-type-inference): You have to pass the `Router` instance to the rest of your application using TypeScript's module declaration.\n3. [**Why push for file-based routing over code-based?**](#3-why-is-file-based-routing-the-preferred-way-to-define-routes): We push for file-based routing as the preferred way to define your routes.\n\n> TLDR; All the design decisions in the developer experience of using TanStack Router are made so that you can have a best-in-class type-safety experience without compromising on the control, flexibility, and maintainability of your route configurations.\n\n## 1. Why is the Router's configuration done this way?\n\nWhen you want to leverage the TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible.\n\nThis means that you have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.\n\n> Can I use JSX to define my routes?\n\nUsing JSX for defining your routes is **out of the question**, as TypeScript will not be able to infer the route configuration types of your router.\n\n```tsx\n// \u26D4\uFE0F This is not possible\nfunction App() {\n return (\n <Router>\n <Route path=\"/posts\" component={PostsPage} />\n <Route path=\"/posts/$postId\" component={PostIdPage} />\n {/* ... */}\n </Router>\n // ^? TypeScript cannot infer the routes in this configuration\n )\n}\n```\n\nAnd since this would mean that you'd have to manually type the `to` prop of the `<Link>` component and wouldn't catch any errors until runtime, it's not a viable option.\n\n> Maybe I could define my routes as a tree of nested objects?\n\n```tsx\n// \u26D4\uFE0F This file will just keep growing and growing...\nconst router = createRouter({\n routes: {\n posts: {\n component: PostsPage, // /posts\n children: {\n $postId: {\n component: PostIdPage, // /posts/$postId\n },\n },\n },\n // ...\n },\n})\n```\n\nAt first glance, this seems like a good idea. It's easy to visualize the entire route hierarchy in one go. But this approach has a couple of big downsides that make it not ideal for large applications:\n\n- **It's not very scalable**: As your application grows, the tree will grow and become harder to manage. And since it's all defined in one file, it can become very hard to maintain.\n- **It's not great for code-splitting**: You'd have to manually code-split each component and then pass it into the `component` property of the route, further complicating the route configuration with an ever-growing route configuration file.\n\nThis only gets worse as you begin to use more features of the router, such as nested context, loaders, search param validation, etc.\n\n> So, what's the best way to define my routes?\n\nWhat we found to be the best way to define your routes is to abstract the definition of the route configuration outside of the route-tree. Then stitch together your route configurations into a single cohesive route-tree that is then passed into the `createRouter` function.\n\nYou can read more about [code-based routing](../routing/code-based-routing.md) to see how to define your routes in this way.\n\n> [!TIP]\n> Finding Code-based routing to be a bit too cumbersome? See why [file-based routing](#3-why-is-file-based-routing-the-preferred-way-to-define-routes) is the preferred way to define your routes.\n\n## 2. Declaring the Router instance for type inference\n\n> Why do I have to declare the `Router`?\n\n> This declaration stuff is way too complicated for me...\n\nOnce you've constructed your routes into a tree and passed it into your Router instance (using `createRouter`) with all the generics working correctly, you then need to somehow pass this information to the rest of your application.\n\nThere were two approaches we considered for this:\n\n1. **Imports**: You could import the `Router` instance from the file where you created it and use it directly in your components.\n\n```tsx\nimport { router } from '@/src/app'\nexport const PostsIdLink = () => {\n return (\n <Link<typeof router> to=\"/posts/$postId\" params={{ postId: '123' }}>\n Go to post 123\n </Link>\n )\n}\n```\n\nA downside to this approach is that you'd have to import the entire `Router` instance into every file where you want to use it. This can lead to increased bundle sizes and can be cumbersome to manage, and only get worse as your application grows and you use more features of the router.\n\n2. **Module declaration**: You can use TypeScript's module declaration to declare the `Router` instance as a module that can be used for type inference anywhere in your application without having to import it.\n\nYou'll do this once in your application.\n\n```tsx\n// src/app.tsx\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n```\n\nAnd then you can benefit from its auto-complete anywhere in your app without having to import it.\n\n```tsx\nexport const PostsIdLink = () => {\n return (\n <Link\n to=\"/posts/$postId\"\n // ^? TypeScript will auto-complete this for you\n params={{ postId: '123' }} // and this too!\n >\n Go to post 123\n </Link>\n )\n}\n```\n\nWe went with **module declaration**, as it is what we found to be the most scalable and maintainable approach with the least amount of overhead and boilerplate.\n\n## 3. Why is file-based routing the preferred way to define routes?\n\n> Why are the docs pushing for file-based routing?\n\n> I'm used to defining my routes in a single file, why should I change?\n\nSomething you'll notice (quite soon) in the TanStack Router documentation is that we push for **file-based routing** as the preferred method for defining your routes. This is because we've found that file-based routing is the most scalable and maintainable way to define your routes.\n\n> [!TIP]\n> Before you continue, it's important you have a good understanding of [code-based routing](../routing/code-based-routing.md) and [file-based routing](../routing/file-based-routing.md).\n\nAs mentioned in the beginning, TanStack Router was designed for complex applications that require a high degree of type-safety and maintainability. And to achieve this, the configuration of the router has been done in a precise way that allows TypeScript to infer the types of your routes as much as possible.\n\nA key difference in the set-up of a _basic_ application with TanStack Router, is that your route configurations require a function to be provided to `getParentRoute`, that returns the parent route of the current route.\n\n```tsx\nimport { createRoute } from '@tanstack/react-router'\nimport { postsRoute } from './postsRoute'\n\nexport const postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n})\n```\n\nAt this stage, this is done so the definition of `postsIndexRoute` can be aware of its location in the route tree and so that it can correctly infer the types of the `context`, `path params`, `search params` returned by the parent route. Incorrectly defining the `getParentRoute` function means that the properties of the parent route will not be correctly inferred by the child route.\n\nAs such, this is a critical part of the route configuration and a point of failure if not done correctly.\n\nBut this is only one part of setting up a basic application. TanStack Router requires all the routes (including the root route) to be stitched into a **_route-tree_** so that it may be passed into the `createRouter` function before declaring the `Router` instance on the module for type inference. This is another critical part of the route configuration and a point of failure if not done correctly.\n\n> \uD83E\uDD2F If this route-tree were in its own file for an application with ~40-50 routes, it can easily grow up to 700+ lines.\n\n```tsx\nconst routeTree = rootRoute.addChildren([\n postsRoute.addChildren([postsIndexRoute, postsIdRoute]),\n])\n```\n\nThis complexity only increases as you begin to use more features of the router, such as nested context, loaders, search param validation, etc. As such, it no longer becomes feasible to define your routes in a single file. And so, users end up building their own _semi consistent_ way of defining their routes across multiple files. This can lead to inconsistencies and errors in the route configuration.\n\nFinally, comes the issue of code-splitting. As your application grows, you'll want to code-split your components to reduce the initial bundle size of your application. This can be a bit of a headache to manage when you're defining your routes in a single file or even across multiple files.\n\n```tsx\nimport { createRoute, lazyRouteComponent } from '@tanstack/react-router'\nimport { postsRoute } from './postsRoute'\n\nexport const postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n component: lazyRouteComponent(() => import('../page-components/posts/index')),\n})\n```\n\nAll of this boilerplate, no matter how essential for providing a best-in-class type-inference experience, can be a bit overwhelming and can lead to inconsistencies and errors in the route configuration.\n\n... and this example configuration is just for rendering a single codes-split route. Imagine having to do this for 40-50 routes. Now remember that you still haven't touched the `context`, `loaders`, `search param validation`, and other features of the router \uD83E\uDD15.\n\n> So, why's file-based routing the preferred way?\n\nTanStack Router's file-based routing is designed to solve all of these issues. It allows you to define your routes in a predictable way that is easy to manage and maintain, and is scalable as your application grows.\n\nThe file-based routing approach is powered by the TanStack Router Bundler Plugin. It performs 3 essential tasks that solve the pain points in route configuration when using code-based routing:\n\n1. **Route configuration boilerplate**: It generates the boilerplate for your route configurations.\n2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function match the routes with their parent routes.\n3. **Code-splitting**: It automatically code-splits your route content components and updates the route configurations with the correct component. Additionally, at runtime, it ensures that the correct component is loaded when the route is visited.\n\nLet's take a look at how the route configuration for the previous example would look like with file-based routing.\n\n```tsx\n// src/routes/posts/index.ts\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/')({\n component: () => 'Posts index component goes here!!!',\n})\n```\n\nThat's it! No need to worry about defining the `getParentRoute` function, stitching together the route-tree, or code-splitting your components. The TanStack Router Bundler Plugin handles all of this for you.\n\nAt no point does the TanStack Router Bundler Plugin take away your control over your route configurations. It's designed to be as flexible as possible, allowing you to define your routes in a way that suits your application whilst reducing the boilerplate and complexity of the route configuration.\n\nCheck out the guides for [file-based routing](../routing/file-based-routing.md) and [code-splitting](../guide/code-splitting.md) for a more in-depth explanation of how they work in TanStack Router.\n\n# Devtools\n\n> Link, take this sword... I mean Devtools!... to help you on your way!\n\nWave your hands in the air and shout hooray because TanStack Router comes with dedicated devtools! \uD83E\uDD73\n\nWhen you begin your TanStack Router journey, you'll want these devtools by your side. They help visualize all of the inner workings of TanStack Router and will likely save you hours of debugging if you find yourself in a pinch!\n\n## Installation\n\nThe devtools are a separate package that you need to install:\n\n```sh\nnpm install @tanstack/react-router-devtools\n```\n\nor\n\n```sh\npnpm add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nyarn add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nbun add @tanstack/react-router-devtools\n```\n\n## Import the Devtools\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n```\n\n## Using Devtools in production\n\nThe Devtools, if imported as `TanStackRouterDevtools` will not be shown in production. If you want to have devtools in an environment with `process.env.NODE_ENV === 'production'`, use instead `TanStackRouterDevtoolsInProd`, which has all the same options:\n\n```tsx\nimport { TanStackRouterDevtoolsInProd } from '@tanstack/react-router-devtools'\n```\n\n## Using inside of the `RouterProvider`\n\nThe easiest way for the devtools to work is to render them inside of your root route (or any other route). This will automatically connect the devtools to the router instance.\n\n```tsx\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst router = createRouter({\n routeTree,\n})\n\nfunction App() {\n return <RouterProvider router={router} />\n}\n```\n\n## Manually passing the Router Instance\n\nIf rendering the devtools inside of the `RouterProvider` isn't your cup of tea, a `router` prop for the devtools accepts the same `router` instance you pass to the `Router` component. This makes it possible to place the devtools anywhere on the page, not just inside the provider:\n\n```tsx\nfunction App() {\n return (\n <>\n <RouterProvider router={router} />\n <TanStackRouterDevtools router={router} />\n </>\n )\n}\n```\n\n## Floating Mode\n\nFloating Mode will mount the devtools as a fixed, floating element in your app and provide a toggle in the corner of the screen to show and hide the devtools. This toggle state will be stored and remembered in localStorage across reloads.\n\nPlace the following code as high in your React app as you can. The closer it is to the root of the page, the better it will work!\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router />\n <TanStackRouterDevtools initialIsOpen={false} />\n </>\n )\n}\n```\n\n### Devtools Options\n\n- `router: Router`\n - The router instance to connect to.\n- `initialIsOpen: Boolean`\n - Set this `true` if you want the devtools to default to being open.\n- `panelProps: PropsObject`\n - Use this to add props to the panel. For example, you can add `className`, `style` (merge and override default style), etc.\n- `closeButtonProps: PropsObject`\n - Use this to add props to the close button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `toggleButtonProps: PropsObject`\n - Use this to add props to the toggle button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `position?: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\"`\n - Defaults to `bottom-left`.\n - The position of the TanStack Router logo to open and close the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n- `containerElement?: string | any`\n - Use this to render the devtools inside a different type of container element for ally purposes.\n - Any string which corresponds to a valid intrinsic JSX element is allowed.\n - Defaults to 'footer'.\n\n## Fixed Mode\n\nTo control the position of the devtools, import the `TanStackRouterDevtoolsPanel`:\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n```\n\nIt can then be attached to provided shadow DOM target:\n\n```js\n<TanStackRouterDevtoolsPanel\n shadowDOMTarget={shadowContainer}\n router={router}\n/>\n```\n\nClick [here](https://tanstack.com/router/latest/docs/framework/react/examples/basic-devtools-panel) to see a live example of this in StackBlitz.\n\n## Embedded Mode\n\nEmbedded Mode will embed the devtools as a regular component in your application. You can style it however you'd like after that!\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router router={router} />\n <TanStackRouterDevtoolsPanel\n router={router}\n style={styles}\n className={className}\n />\n </>\n )\n}\n```\n\n### DevtoolsPanel Options\n\n- `router: Router`\n - The router instance to connect to.\n- `style: StyleObject`\n - The standard React style object used to style a component with inline styles.\n- `className: string`\n - The standard React className property used to style a component with classes.\n- `isOpen?: boolean`\n - A boolean variable indicating whether the panel is open or closed.\n- `setIsOpen?: (isOpen: boolean) => void`\n - A function that toggles the open and close state of the panel.\n- `handleDragStart?: (e: any) => void`\n - Handles the opening and closing the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n\n# Frequently Asked Questions\n\nWelcome to the TanStack Router FAQ! Here you'll find answers to common questions about the TanStack Router. If you have a question that isn't answered here, please feel free to ask in the [TanStack Discord](https://tlinz.com/discord).\n\n## Why should you choose TanStack Router over another router?\n\nTo answer this question, it's important to view the other options in the space. There are many alternatives to choose from, but only a couple that are widely adopted and actively maintained:\n\n- **Next.js** - Widely regarded as the leading framework for starting new React projects. Its design focuses on performance, development workflows, and cutting-edge technology. The framework's APIs and abstractions, while powerful, can sometimes present as non-standard. Rapid growth and industry adoption have resulted in a feature-rich experience, sometimes leading to a steeper learning curve and increased overhead.\n- **Remix / React Router** - Based on the historically successful React Router, Remix delivers a powerful developer and user experience. Its API and architectural vision are firmly rooted in web standards such as Request/Response, with an emphasis on adaptability across various JavaScript environments. Many of its APIs and abstractions are well-designed and have influenced more than a few of TanStack Router's APIs. However, its rigid design, the integration of type safety as an add-on, and sometimes strict adherence to platform APIs can present limitations for some developers.\n\nThese frameworks and routers have their strengths, but they also come with trade-offs that may not align with every project's needs. TanStack Router aims to strike a balance by offering routing APIs designed to improve the developer experience without sacrificing flexibility or performance.\n\n## Is TanStack Router a framework?\n\nTanStack Router itself is not a \"framework\" in the traditional sense, since it doesn't address a few other common full-stack concerns. However, TanStack Router has been designed to be upgradable to a full-stack framework when used in conjunction with other tools that address bundling, deployments, and server-side-specific functionality. This is why we are currently developing [TanStack Start](https://tanstack.com/start), a full-stack framework that is built on top of TanStack Router and Vite.\nFor a deeper dive on the history of TanStack Router, feel free to read [TanStack Router's History](../decisions-on-dx.md#tanstack-routers-origin-story).\n\n## Should I commit my `routeTree.gen.ts` file into git?\n\nYes! Although the route tree file (i.e., `routeTree.gen.ts`) is generated by TanStack Router, it is essentially part of your application\u2019s runtime, not a build artifact. The route tree file is a critical part of your application\u2019s source code, and it is used by TanStack Router to build your application\u2019s routes at runtime.\n\nYou should commit this file into git so that other developers can use it to build your application.\n\n## Can I conditionally render the Root Route component?\n\nNo, the root route is always rendered as it is the entry point of your application.\n\nIf you need to conditionally render a route's component, this usually means that the page content needs to be different based on some condition (e.g. user authentication). For this use case, you should use a [Layout Route](../routing/routing-concepts.md#layout-routes) or a [Pathless Layout Route](../routing/routing-concepts.md#pathless-layout-routes) to conditionally render the content.\n\nYou can restrict access to these routes using a conditional check in the `beforeLoad` function of the route.\n\n<details>\n<summary>What does this look like?</summary>\n\n```tsx\n// src/routes/_pathless-layout.tsx\nimport { createFileRoute, Outlet } from '@tanstack/react-router'\nimport { isAuthenticated } from '../utils/auth'\n\nexport const Route = createFileRoute('/_pathless-layout', {\n beforeLoad: async () => {\n // Check if the user is authenticated\n const authed = await isAuthenticated()\n if (!authed) {\n // Redirect the user to the login page\n return '/login'\n }\n },\n component: PathlessLayoutRouteComponent,\n // ...\n})\n\nfunction PathlessLayoutRouteComponent() {\n return (\n <div>\n <h1>You are authed</h1>\n <Outlet />\n </div>\n )\n}\n```\n\n</details>\n\n";
|
|
1
|
+
declare const _default: "# Overview\n\n**TanStack Router is a router for building React and Solid applications**. Some of its features include:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Nested Routing and layout routes (with pathless layouts)\n- Built-in Route Loaders w/ SWR Caching\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Automatic route prefetching\n- Asynchronous route elements and error boundaries\n- File-based Route Generation\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Param Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Route matching/loading middleware\n\nTo get started quickly, head to the next page. For a more lengthy explanation, buckle up while I bring you up to speed!\n\n## \"A Fork in the Route\"\n\nUsing a router to build applications is widely regarded as a must-have and is usually one of the first choices you\u2019ll make in your tech stack.\n\n## Why TanStack Router?\n\nTanStack Router delivers on the same fundamental expectations as other routers that you\u2019ve come to expect:\n\n- Nested routes, layout routes, grouped routes\n- File-based Routing\n- Parallel data loading\n- Prefetching\n- URL Path Params\n- Error Boundaries and Handling\n- SSR\n- Route Masking\n\nAnd it also delivers some new features that raise the bar:\n\n- 100% inferred TypeScript support\n- Typesafe navigation\n- Built-in SWR Caching for loaders\n- Designed for client-side data caches (TanStack Query, SWR, etc.)\n- Typesafe JSON-first Search Params state management APIs\n- Path and Search Parameter Schema Validation\n- Search Parameter Navigation APIs\n- Custom Search Param parser/serializer support\n- Search param middleware\n- Inherited Route Context\n- Mixed file-based and code-based routing\n\nLet\u2019s dive into some of the more important ones in more detail!\n\n## 100% Inferred TypeScript Support\n\nEverything these days is written \u201Cin Typescript\u201D or at the very least offers type definitions that are veneered over runtime functionality, but too few packages in the ecosystem actually design their APIs with TypeScript in mind. So while I\u2019m pleased that your router is auto-completing your option fields and catching a few property/method typos here and there, there is much more to be had.\n\n- TanStack Router is fully aware of all of your routes and their configuration at any given point in your code. This includes the path, path params, search params, context, and any other configuration you\u2019ve provided. Ultimately this means that you can navigate to any route in your app with 100% type safety and confidence that your link or navigate call will succeed.\n- TanStack Router provides lossless type-inference. It uses countless generic type parameters to enforce and propagate any type information you give it throughout the rest of its API and ultimately your app. No other router offers this level of type safety and developer confidence.\n\nWhat does all of that mean for you?\n\n- Faster feature development with auto-completion and type hints\n- Safer and faster refactors\n- Confidence that your code will work as expected\n\n## 1st Class Search Parameters\n\nSearch parameters are often an afterthought, treated like a black box of strings (or string) that you can parse and update, but not much else. Existing solutions are **not** type-safe either, adding to the caution that is required to deal with them. Even the most \"modern\" frameworks and routers leave it up to you to figure out how to manage this state. Sometimes they'll parse the search string into an object for you, or sometimes you're left to do it yourself with `URLSearchParams`.\n\nLet's step back and remember that **search params are the most powerful state manager in your entire application.** They are global, serializable, bookmarkable, and shareable making them the perfect place to store any kind of state that needs to survive a page refresh or a social share.\n\nTo live up to that responsibility, search parameters are a first-class citizen in TanStack Router. While still based on standard URLSearchParams, TanStack Router uses a powerful parser/serializer to manage deeper and more complex data structures in your search params, all while keeping them type-safe and easy to work with.\n\n**It's like having `useState` right in the URL!**\n\nSearch parameters are:\n\n- Automatically parsed and serialized as JSON\n- Validated and typed\n- Inherited from parent routes\n- Accessible in loaders, components, and hooks\n- Easily modified with the useSearch hook, Link, navigate, and router.navigate APIs\n- Customizable with a custom search filters and middleware\n- Subscribed via fine-grained search param selectors for efficient re-renders\n\nOnce you start using TanStack Router's search parameters, you'll wonder how you ever lived without them.\n\n## Built-In Caching and Friendly Data Loading\n\nData loading is a critical part of any application and while most existing routers offer some form of critical data loading APIs, they often fall short when it comes to caching and data lifecycle management. Existing solutions suffer from a few common problems:\n\n- No caching at all. Data is always fresh, but your users are left waiting for frequently accessed data to load over and over again.\n- Overly-aggressive caching. Data is cached for too long, leading to stale data and a poor user experience.\n- Blunt invalidation strategies and APIs. Data may be invalidated too often, leading to unnecessary network requests and wasted resources, or you may not have any fine-grained control over when data is invalidated at all.\n\nTanStack Router solves these problems with a two-prong approach to caching and data loading:\n\n### Built-in Cache\n\nTanStack Router provides a light-weight built-in caching layer that works seamlessly with the Router. This caching layer is loosely based on TanStack Query, but with fewer features and a much smaller API surface area. Like TanStack Query, sane but powerful defaults guarantee that your data is cached for reuse, invalidated when necessary, and garbage collected when not in use. It also provides a simple API for invalidating the cache manually when needed.\n\n### Flexible & Powerful Data Lifecycle APIs\n\nTanStack Router is designed with a flexible and powerful data loading API that more easily integrates with existing data fetching libraries like TanStack Query, SWR, Apollo, Relay, or even your own custom data fetching solution. Configurable APIs like `context`, `beforeLoad`, `loaderDeps` and `loader` work in unison to make it easy to define declarative data dependencies, prefetch data, and manage the lifecycle of an external data source with ease.\n\n## Inherited Route Context\n\nTanStack Router's router and route context is a powerful feature that allows you to define context that is specific to a route which is then inherited by all child routes. Even the router and root routes themselves can provide context. Context can be built up both synchronously and asynchronously, and can be used to share data, configuration, or even functions between routes and route configurations. This is especially useful for scenarios like:\n\n- Authentication and Authorization\n- Hybrid SSR/CSR data fetching and preloading\n- Theming\n- Singletons and global utilities\n- Curried or partial application across preloading, loading, and rendering stages\n\nAlso, what would route context be if it weren't type-safe? TanStack Router's route context is fully type-safe and inferred at zero cost to you.\n\n## File-based and/or Code-Based Routing\n\nTanStack Router supports both file-based and code-based routing at the same time. This flexibility allows you to choose the approach that best fits your project's needs.\n\nTanStack Router's file-based routing approach is uniquely user-facing. Route configuration is generated for you either by the Vite plugin or TanStack Router CLI, leaving the usage of said generated code up to you! This means that you're always in total control of your routes and router, even if you use file-based routing.\n\n## Acknowledgements\n\nTanStack Router builds on concepts and patterns popularized by many other OSS projects, including:\n\n- [TRPC](https://trpc.io/)\n- [Remix](https://remix.run)\n- [Chicane](https://swan-io.github.io/chicane/)\n- [Next.js](https://nextjs.org)\n\nWe acknowledge the investment, risk and research that went into their development, but are excited to push the bar they have set even higher.\n\n## Let's go!\n\nEnough overview, there's so much more to do with TanStack Router. Hit that next button and let's get started!\n\n# Quick Start\n\nTanStack Router can be quickly added to any existing React project or used to scaffold a new one.\n\n## TanStack Router Installation\n\n### Requirements\n\nBefore installing TanStack router, please ensure your project meets the following requirements:\n\n[//]: # 'Requirements'\n\n- `react` v18 or later with `createRoot` support.\n- `react-dom` v18 or later.\n\n[//]: # 'Requirements'\n\n> [!NOTE] Using TypeScript (`v5.3.x or higher`) is recommended for the best development experience, though not strictly required. We aim to support the last 5 minor versions of TypeScript, but using the latest version will help avoid potential issues.\n\nTanStack Router is currently only compatible with React (with ReactDOM) and Solid. If you're interested in contributing to support other frameworks, such as React Native, Angular, or Vue, please reach out to us on [Discord](https://tlinz.com/discord).\n\n### Download and Install\n\nTo install TanStack Router in your project, run the following command using your preferred package manager:\n\n[//]: # 'installCommand'\n\n```sh\nnpm install @tanstack/react-router\n# or\npnpm add @tanstack/react-router\n#or\nyarn add @tanstack/react-router\n# or\nbun add @tanstack/react-router\n# or\ndeno add npm:@tanstack/react-router\n```\n\n[//]: # 'installCommand'\n\nOnce installed, you can verify the installation by checking your `package.json` file for the dependency.\n\n[//]: # 'packageJson'\n\n```json\n{\n \"dependencies\": {\n \"@tanstack/react-router\": \"^x.x.x\"\n }\n}\n```\n\n[//]: # 'packageJson'\n\n## New Project Setup\n\nTo quickly scaffold a new project with TanStack Router, you can use the `create-tsrouter-app` command-line tool. This tool sets up a new React application with TanStack Router pre-configured, allowing you to get started quickly.\n\n> [!TIP] For full details on available options and templates, visit the [`create-tsrouter-app` documentation](https://github.com/TanStack/create-tsrouter-app/tree/main/cli/create-tsrouter-app).\n\nTo create a new project, run the following command in your terminal:\n\n[//]: # 'createAppCommand'\n\n```sh\nnpx create-tsrouter-app@latest\n```\n\n[//]: # 'createAppCommand'\n\nThe CLI will guide you through a short series of prompts to customize your setup, including options for:\n\n[//]: # 'CLIPrompts'\n\n- File-based or code-based route configuration\n- TypeScript support\n- Tailwind CSS integration\n- Toolchain setup\n- Git initialization\n\n[//]: # 'CLIPrompts'\n\nOnce complete, a new React project will be generated with TanStack Router installed and ready to use. All dependencies are automatically installed, so you can jump straight into development:\n\n```sh\ncd your-project-name\nnpm run dev\n```\n\n### Routing Options\n\nTanStack Router supports both file-based and code-based route configurations, allowing you to choose the approach that best fits your workflow.\n\n#### File-Based Route Generation\n\nThe file-based approach is the recommended option for most projects. It automatically creates routes based on your file structure, giving you the best mix of performance, simplicity, and developer experience.\n\nTo create a new project using file-based route generation, run the following command:\n\n[//]: # 'createAppCommandFileBased'\n\n```sh\nnpx create-tsrouter-app@latest my-app --template file-router\n```\n\n[//]: # 'createAppCommandFileBased'\n\nThis command sets up a new directory called `my-app` with everything configured. Once setup completes, you can then start your development server and begin building your application:\n\n```sh\ncd my-app\nnpm run dev\n```\n\n#### Code-Based Route Configuration\n\nIf you prefer to define routes programmatically, you can use the code-based route configuration. This approach gives you full control over routing logic while maintaining the same project scaffolding workflow.\n\n[//]: # 'createAppCommandCodeBased'\n\n```sh\nnpx create-tsrouter-app@latest my-app\n```\n\n[//]: # 'createAppCommandCodeBased'\n\nSimilar to the file-based setup, this command creates a new directory called `my-app` with TanStack Router configured for code-based routing. After setup, navigate to your project directory and start the development server:\n\n```sh\ncd my-app\nnpm run dev\n```\n\nWith either approach, you can now start building your React application with TanStack Router!\n\n# Decisions on Developer Experience\n\nWhen people first start using TanStack Router, they often have a lot of questions that revolve around the following themes:\n\n> Why do I have to do things this way?\n\n> Why is it done this way? and not that way?\n\n> I'm used to doing it this way, why should I change?\n\nAnd they are all valid questions. For the most part, people are used to using routing libraries that are very similar to each other. They all have a similar API, similar concepts, and similar ways of doing things.\n\nBut TanStack Router is different. It's not your average routing library. It's not your average state management library. It's not your average anything.\n\n## TanStack Router's origin story\n\nIt's important to remember that TanStack Router's origins stem from [Nozzle.io](https://nozzle.io)'s need for a client-side routing solution that offered a first-in-class _URL Search Parameters_ experience without compromising on the **_type-safety_** that was required to power its complex dashboards.\n\nAnd so, from TanStack Router's very inception, every facet of its design was meticulously thought out to ensure that its type-safety and developer experience were second to none.\n\n## How does TanStack Router achieve this?\n\n> TypeScript! TypeScript! TypeScript!\n\nEvery aspect of TanStack Router is designed to be as type-safe as possible, and this is achieved by leveraging TypeScript's type system to its fullest extent. This involves using some very advanced and complex types, type inference, and other features to ensure that the developer experience is as smooth as possible.\n\nBut to achieve this, we had to make some decisions that deviate from the norms in the routing world.\n\n1. [**Route configuration boilerplate?**](#1-why-is-the-routers-configuration-done-this-way): You have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.\n2. [**TypeScript module declaration for the router?**](#2-declaring-the-router-instance-for-type-inference): You have to pass the `Router` instance to the rest of your application using TypeScript's module declaration.\n3. [**Why push for file-based routing over code-based?**](#3-why-is-file-based-routing-the-preferred-way-to-define-routes): We push for file-based routing as the preferred way to define your routes.\n\n> TLDR; All the design decisions in the developer experience of using TanStack Router are made so that you can have a best-in-class type-safety experience without compromising on the control, flexibility, and maintainability of your route configurations.\n\n## 1. Why is the Router's configuration done this way?\n\nWhen you want to leverage the TypeScript's inference features to its fullest, you'll quickly realize that _Generics_ are your best friend. And so, TanStack Router uses Generics everywhere to ensure that the types of your routes are inferred as much as possible.\n\nThis means that you have to define your routes in a way that allows TypeScript to infer the types of your routes as much as possible.\n\n> Can I use JSX to define my routes?\n\nUsing JSX for defining your routes is **out of the question**, as TypeScript will not be able to infer the route configuration types of your router.\n\n```tsx\n// \u26D4\uFE0F This is not possible\nfunction App() {\n return (\n <Router>\n <Route path=\"/posts\" component={PostsPage} />\n <Route path=\"/posts/$postId\" component={PostIdPage} />\n {/* ... */}\n </Router>\n // ^? TypeScript cannot infer the routes in this configuration\n )\n}\n```\n\nAnd since this would mean that you'd have to manually type the `to` prop of the `<Link>` component and wouldn't catch any errors until runtime, it's not a viable option.\n\n> Maybe I could define my routes as a tree of nested objects?\n\n```tsx\n// \u26D4\uFE0F This file will just keep growing and growing...\nconst router = createRouter({\n routes: {\n posts: {\n component: PostsPage, // /posts\n children: {\n $postId: {\n component: PostIdPage, // /posts/$postId\n },\n },\n },\n // ...\n },\n})\n```\n\nAt first glance, this seems like a good idea. It's easy to visualize the entire route hierarchy in one go. But this approach has a couple of big downsides that make it not ideal for large applications:\n\n- **It's not very scalable**: As your application grows, the tree will grow and become harder to manage. And since it's all defined in one file, it can become very hard to maintain.\n- **It's not great for code-splitting**: You'd have to manually code-split each component and then pass it into the `component` property of the route, further complicating the route configuration with an ever-growing route configuration file.\n\nThis only gets worse as you begin to use more features of the router, such as nested context, loaders, search param validation, etc.\n\n> So, what's the best way to define my routes?\n\nWhat we found to be the best way to define your routes is to abstract the definition of the route configuration outside of the route-tree. Then stitch together your route configurations into a single cohesive route-tree that is then passed into the `createRouter` function.\n\nYou can read more about [code-based routing](../routing/code-based-routing.md) to see how to define your routes in this way.\n\n> [!TIP]\n> Finding Code-based routing to be a bit too cumbersome? See why [file-based routing](#3-why-is-file-based-routing-the-preferred-way-to-define-routes) is the preferred way to define your routes.\n\n## 2. Declaring the Router instance for type inference\n\n> Why do I have to declare the `Router`?\n\n> This declaration stuff is way too complicated for me...\n\nOnce you've constructed your routes into a tree and passed it into your Router instance (using `createRouter`) with all the generics working correctly, you then need to somehow pass this information to the rest of your application.\n\nThere were two approaches we considered for this:\n\n1. **Imports**: You could import the `Router` instance from the file where you created it and use it directly in your components.\n\n```tsx\nimport { router } from '@/src/app'\nexport const PostsIdLink = () => {\n return (\n <Link<typeof router> to=\"/posts/$postId\" params={{ postId: '123' }}>\n Go to post 123\n </Link>\n )\n}\n```\n\nA downside to this approach is that you'd have to import the entire `Router` instance into every file where you want to use it. This can lead to increased bundle sizes and can be cumbersome to manage, and only get worse as your application grows and you use more features of the router.\n\n2. **Module declaration**: You can use TypeScript's module declaration to declare the `Router` instance as a module that can be used for type inference anywhere in your application without having to import it.\n\nYou'll do this once in your application.\n\n```tsx\n// src/app.tsx\ndeclare module '@tanstack/react-router' {\n interface Register {\n router: typeof router\n }\n}\n```\n\nAnd then you can benefit from its auto-complete anywhere in your app without having to import it.\n\n```tsx\nexport const PostsIdLink = () => {\n return (\n <Link\n to=\"/posts/$postId\"\n // ^? TypeScript will auto-complete this for you\n params={{ postId: '123' }} // and this too!\n >\n Go to post 123\n </Link>\n )\n}\n```\n\nWe went with **module declaration**, as it is what we found to be the most scalable and maintainable approach with the least amount of overhead and boilerplate.\n\n## 3. Why is file-based routing the preferred way to define routes?\n\n> Why are the docs pushing for file-based routing?\n\n> I'm used to defining my routes in a single file, why should I change?\n\nSomething you'll notice (quite soon) in the TanStack Router documentation is that we push for **file-based routing** as the preferred method for defining your routes. This is because we've found that file-based routing is the most scalable and maintainable way to define your routes.\n\n> [!TIP]\n> Before you continue, it's important you have a good understanding of [code-based routing](../routing/code-based-routing.md) and [file-based routing](../routing/file-based-routing.md).\n\nAs mentioned in the beginning, TanStack Router was designed for complex applications that require a high degree of type-safety and maintainability. And to achieve this, the configuration of the router has been done in a precise way that allows TypeScript to infer the types of your routes as much as possible.\n\nA key difference in the set-up of a _basic_ application with TanStack Router, is that your route configurations require a function to be provided to `getParentRoute`, that returns the parent route of the current route.\n\n```tsx\nimport { createRoute } from '@tanstack/react-router'\nimport { postsRoute } from './postsRoute'\n\nexport const postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n})\n```\n\nAt this stage, this is done so the definition of `postsIndexRoute` can be aware of its location in the route tree and so that it can correctly infer the types of the `context`, `path params`, `search params` returned by the parent route. Incorrectly defining the `getParentRoute` function means that the properties of the parent route will not be correctly inferred by the child route.\n\nAs such, this is a critical part of the route configuration and a point of failure if not done correctly.\n\nBut this is only one part of setting up a basic application. TanStack Router requires all the routes (including the root route) to be stitched into a **_route-tree_** so that it may be passed into the `createRouter` function before declaring the `Router` instance on the module for type inference. This is another critical part of the route configuration and a point of failure if not done correctly.\n\n> \uD83E\uDD2F If this route-tree were in its own file for an application with ~40-50 routes, it can easily grow up to 700+ lines.\n\n```tsx\nconst routeTree = rootRoute.addChildren([\n postsRoute.addChildren([postsIndexRoute, postsIdRoute]),\n])\n```\n\nThis complexity only increases as you begin to use more features of the router, such as nested context, loaders, search param validation, etc. As such, it no longer becomes feasible to define your routes in a single file. And so, users end up building their own _semi consistent_ way of defining their routes across multiple files. This can lead to inconsistencies and errors in the route configuration.\n\nFinally, comes the issue of code-splitting. As your application grows, you'll want to code-split your components to reduce the initial bundle size of your application. This can be a bit of a headache to manage when you're defining your routes in a single file or even across multiple files.\n\n```tsx\nimport { createRoute, lazyRouteComponent } from '@tanstack/react-router'\nimport { postsRoute } from './postsRoute'\n\nexport const postsIndexRoute = createRoute({\n getParentRoute: () => postsRoute,\n path: '/',\n component: lazyRouteComponent(() => import('../page-components/posts/index')),\n})\n```\n\nAll of this boilerplate, no matter how essential for providing a best-in-class type-inference experience, can be a bit overwhelming and can lead to inconsistencies and errors in the route configuration.\n\n... and this example configuration is just for rendering a single codes-split route. Imagine having to do this for 40-50 routes. Now remember that you still haven't touched the `context`, `loaders`, `search param validation`, and other features of the router \uD83E\uDD15.\n\n> So, why's file-based routing the preferred way?\n\nTanStack Router's file-based routing is designed to solve all of these issues. It allows you to define your routes in a predictable way that is easy to manage and maintain, and is scalable as your application grows.\n\nThe file-based routing approach is powered by the TanStack Router Bundler Plugin. It performs 3 essential tasks that solve the pain points in route configuration when using code-based routing:\n\n1. **Route configuration boilerplate**: It generates the boilerplate for your route configurations.\n2. **Route tree stitching**: It stitches together your route configurations into a single cohesive route-tree. Also in the background, it correctly updates the route configurations to define the `getParentRoute` function match the routes with their parent routes.\n3. **Code-splitting**: It automatically code-splits your route content components and updates the route configurations with the correct component. Additionally, at runtime, it ensures that the correct component is loaded when the route is visited.\n\nLet's take a look at how the route configuration for the previous example would look like with file-based routing.\n\n```tsx\n// src/routes/posts/index.ts\nimport { createFileRoute } from '@tanstack/react-router'\n\nexport const Route = createFileRoute('/posts/')({\n component: () => 'Posts index component goes here!!!',\n})\n```\n\nThat's it! No need to worry about defining the `getParentRoute` function, stitching together the route-tree, or code-splitting your components. The TanStack Router Bundler Plugin handles all of this for you.\n\nAt no point does the TanStack Router Bundler Plugin take away your control over your route configurations. It's designed to be as flexible as possible, allowing you to define your routes in a way that suits your application whilst reducing the boilerplate and complexity of the route configuration.\n\nCheck out the guides for [file-based routing](../routing/file-based-routing.md) and [code-splitting](../guide/code-splitting.md) for a more in-depth explanation of how they work in TanStack Router.\n\n# Devtools\n\n> Link, take this sword... I mean Devtools!... to help you on your way!\n\nWave your hands in the air and shout hooray because TanStack Router comes with dedicated devtools! \uD83E\uDD73\n\nWhen you begin your TanStack Router journey, you'll want these devtools by your side. They help visualize all of the inner workings of TanStack Router and will likely save you hours of debugging if you find yourself in a pinch!\n\n## Installation\n\nThe devtools are a separate package that you need to install:\n\n```sh\nnpm install @tanstack/react-router-devtools\n```\n\nor\n\n```sh\npnpm add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nyarn add @tanstack/react-router-devtools\n```\n\nor\n\n```sh\nbun add @tanstack/react-router-devtools\n```\n\n## Import the Devtools\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n```\n\n## Using Devtools in production\n\nThe Devtools, if imported as `TanStackRouterDevtools` will not be shown in production. If you want to have devtools in an environment with `process.env.NODE_ENV === 'production'`, use instead `TanStackRouterDevtoolsInProd`, which has all the same options:\n\n```tsx\nimport { TanStackRouterDevtoolsInProd } from '@tanstack/react-router-devtools'\n```\n\n## Using inside of the `RouterProvider`\n\nThe easiest way for the devtools to work is to render them inside of your root route (or any other route). This will automatically connect the devtools to the router instance.\n\n```tsx\nconst rootRoute = createRootRoute({\n component: () => (\n <>\n <Outlet />\n <TanStackRouterDevtools />\n </>\n ),\n})\n\nconst routeTree = rootRoute.addChildren([\n // ... other routes\n])\n\nconst router = createRouter({\n routeTree,\n})\n\nfunction App() {\n return <RouterProvider router={router} />\n}\n```\n\n## Manually passing the Router Instance\n\nIf rendering the devtools inside of the `RouterProvider` isn't your cup of tea, a `router` prop for the devtools accepts the same `router` instance you pass to the `Router` component. This makes it possible to place the devtools anywhere on the page, not just inside the provider:\n\n```tsx\nfunction App() {\n return (\n <>\n <RouterProvider router={router} />\n <TanStackRouterDevtools router={router} />\n </>\n )\n}\n```\n\n## Floating Mode\n\nFloating Mode will mount the devtools as a fixed, floating element in your app and provide a toggle in the corner of the screen to show and hide the devtools. This toggle state will be stored and remembered in localStorage across reloads.\n\nPlace the following code as high in your React app as you can. The closer it is to the root of the page, the better it will work!\n\n```js\nimport { TanStackRouterDevtools } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router />\n <TanStackRouterDevtools initialIsOpen={false} />\n </>\n )\n}\n```\n\n### Devtools Options\n\n- `router: Router`\n - The router instance to connect to.\n- `initialIsOpen: Boolean`\n - Set this `true` if you want the devtools to default to being open.\n- `panelProps: PropsObject`\n - Use this to add props to the panel. For example, you can add `className`, `style` (merge and override default style), etc.\n- `closeButtonProps: PropsObject`\n - Use this to add props to the close button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `toggleButtonProps: PropsObject`\n - Use this to add props to the toggle button. For example, you can add `className`, `style` (merge and override default style), `onClick` (extend default handler), etc.\n- `position?: \"top-left\" | \"top-right\" | \"bottom-left\" | \"bottom-right\"`\n - Defaults to `bottom-left`.\n - The position of the TanStack Router logo to open and close the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n- `containerElement?: string | any`\n - Use this to render the devtools inside a different type of container element for ally purposes.\n - Any string which corresponds to a valid intrinsic JSX element is allowed.\n - Defaults to 'footer'.\n\n## Fixed Mode\n\nTo control the position of the devtools, import the `TanStackRouterDevtoolsPanel`:\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n```\n\nIt can then be attached to provided shadow DOM target:\n\n```js\n<TanStackRouterDevtoolsPanel\n shadowDOMTarget={shadowContainer}\n router={router}\n/>\n```\n\nClick [here](https://tanstack.com/router/latest/docs/framework/react/examples/basic-devtools-panel) to see a live example of this in StackBlitz.\n\n## Embedded Mode\n\nEmbedded Mode will embed the devtools as a regular component in your application. You can style it however you'd like after that!\n\n```js\nimport { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'\n\nfunction App() {\n return (\n <>\n <Router router={router} />\n <TanStackRouterDevtoolsPanel\n router={router}\n style={styles}\n className={className}\n />\n </>\n )\n}\n```\n\n### DevtoolsPanel Options\n\n- `router: Router`\n - The router instance to connect to.\n- `style: StyleObject`\n - The standard React style object used to style a component with inline styles.\n- `className: string`\n - The standard React className property used to style a component with classes.\n- `isOpen?: boolean`\n - A boolean variable indicating whether the panel is open or closed.\n- `setIsOpen?: (isOpen: boolean) => void`\n - A function that toggles the open and close state of the panel.\n- `handleDragStart?: (e: any) => void`\n - Handles the opening and closing the devtools panel.\n- `shadowDOMTarget?: ShadowRoot`\n - Specifies a Shadow DOM target for the devtools.\n - By default, devtool styles are applied to the `<head>` tag of the main document (light DOM). When a `shadowDOMTarget` is provided, styles will be applied within this Shadow DOM instead.\n\n# Frequently Asked Questions\n\nWelcome to the TanStack Router FAQ! Here you'll find answers to common questions about the TanStack Router. If you have a question that isn't answered here, please feel free to ask in the [TanStack Discord](https://tlinz.com/discord).\n\n## Why should you choose TanStack Router over another router?\n\nTo answer this question, it's important to view the other options in the space. There are many alternatives to choose from, but only a couple that are widely adopted and actively maintained:\n\n- **Next.js** - Widely regarded as the leading framework for starting new React projects. Its design focuses on performance, development workflows, and cutting-edge technology. The framework's APIs and abstractions, while powerful, can sometimes present as non-standard. Rapid growth and industry adoption have resulted in a feature-rich experience, sometimes leading to a steeper learning curve and increased overhead.\n- **Remix / React Router** - Based on the historically successful React Router, Remix delivers a powerful developer and user experience. Its API and architectural vision are firmly rooted in web standards such as Request/Response, with an emphasis on adaptability across various JavaScript environments. Many of its APIs and abstractions are well-designed and have influenced more than a few of TanStack Router's APIs. However, its rigid design, the integration of type safety as an add-on, and sometimes strict adherence to platform APIs can present limitations for some developers.\n\nThese frameworks and routers have their strengths, but they also come with trade-offs that may not align with every project's needs. TanStack Router aims to strike a balance by offering routing APIs designed to improve the developer experience without sacrificing flexibility or performance.\n\n## Is TanStack Router a framework?\n\nTanStack Router itself is not a \"framework\" in the traditional sense, since it doesn't address a few other common full-stack concerns. However, TanStack Router has been designed to be upgradable to a full-stack framework when used in conjunction with other tools that address bundling, deployments, and server-side-specific functionality. This is why we are currently developing [TanStack Start](https://tanstack.com/start), a full-stack framework that is built on top of TanStack Router and Vite.\nFor a deeper dive on the history of TanStack Router, feel free to read [TanStack Router's History](../decisions-on-dx.md#tanstack-routers-origin-story).\n\n## Should I commit my `routeTree.gen.ts` file into git?\n\nYes! Although the route tree file (i.e., `routeTree.gen.ts`) is generated by TanStack Router, it is essentially part of your application\u2019s runtime, not a build artifact. The route tree file is a critical part of your application\u2019s source code, and it is used by TanStack Router to build your application\u2019s routes at runtime.\n\nYou should commit this file into git so that other developers can use it to build your application.\n\n## Can I conditionally render the Root Route component?\n\nNo, the root route is always rendered as it is the entry point of your application.\n\nIf you need to conditionally render a route's component, this usually means that the page content needs to be different based on some condition (e.g. user authentication). For this use case, you should use a [Layout Route](../routing/routing-concepts.md#layout-routes) or a [Pathless Layout Route](../routing/routing-concepts.md#pathless-layout-routes) to conditionally render the content.\n\nYou can restrict access to these routes using a conditional check in the `beforeLoad` function of the route.\n\n<details>\n<summary>What does this look like?</summary>\n\n```tsx\n// src/routes/_pathless-layout.tsx\nimport { createFileRoute, Outlet } from '@tanstack/react-router'\nimport { isAuthenticated } from '../utils/auth'\n\nexport const Route = createFileRoute('/_pathless-layout', {\n beforeLoad: async () => {\n // Check if the user is authenticated\n const authed = await isAuthenticated()\n if (!authed) {\n // Redirect the user to the login page\n return '/login'\n }\n },\n component: PathlessLayoutRouteComponent,\n // ...\n})\n\nfunction PathlessLayoutRouteComponent() {\n return (\n <div>\n <h1>You are authed</h1>\n <Outlet />\n </div>\n )\n}\n```\n\n</details>\n\n";
|
|
2
2
|
export default _default;
|
|
@@ -23,27 +23,6 @@ To get started quickly, head to the next page. For a more lengthy explanation, b
|
|
|
23
23
|
|
|
24
24
|
Using a router to build applications is widely regarded as a must-have and is usually one of the first choices you’ll make in your tech stack.
|
|
25
25
|
|
|
26
|
-
[//]: # 'WhyChooseTanStackRouter'
|
|
27
|
-
|
|
28
|
-
**So, why should you choose TanStack Router over another router?**
|
|
29
|
-
|
|
30
|
-
To answer this question, we need to look at the other options in the space. There are many if you look hard enough, but in my experience, only a couple are worth exploring seriously:
|
|
31
|
-
|
|
32
|
-
- **Next.js** - Widely regarded as the de facto framework for starting a new React project, it’s laser focused on performance, workflow, and bleeding edge technology. Its APIs and abstractions are powerful, but can sometimes come across as non-standard. Its extremely fast growth and adoption in the industry has resulted in a featured packed experience, but at the expense of feeling overwhelming and sometimes bloated.
|
|
33
|
-
- **Remix / React Router** - A full-stack framework based on the historically successful React Router offers a similarly powerful developer and user experience, with APIs and vision based firmly on web standards like Request/Response and a focus on running anywhere JS can run. Many of its APIs and abstractions are wonderfully designed and were inspiration for more than a few TanStack Router APIs. That said, its rigid design, bolted-on type safety and sometimes strict over-adherence to platform APIs can leave some developers wanting more.
|
|
34
|
-
|
|
35
|
-
Both of these frameworks (and their routers) are great, and I can personally attest that both are very good solutions for building React applications. My experience has also taught me that these solutions could also be much better, especially around the actual routing APIs that are available to developers to make their apps faster, easier, and more enjoyable to work with.
|
|
36
|
-
|
|
37
|
-
It's probably no surprise at this point that picking a router is so important that it is often tied 1-to-1 with your choice of framework, since most frameworks rely on a specific router.
|
|
38
|
-
|
|
39
|
-
[//]: # 'WhyChooseTanStackRouter'
|
|
40
|
-
|
|
41
|
-
**Does this mean that TanStack Router is a framework?**
|
|
42
|
-
|
|
43
|
-
TanStack Router itself is not a "framework" in the traditional sense, since it doesn't address a few other common full-stack concerns. However TanStack Router has been designed to be upgradable to a full-stack framework when used in conjunction with other tools that address bundling, deployments, and server-side-specific functionality. This is why we are currently developing [TanStack Start](https://tanstack.com/start), a full-stack framework that is built on top of TanStack Router and Vite.
|
|
44
|
-
|
|
45
|
-
For a deeper dive on the history of TanStack Router, feel free to read [TanStack Router's History](../decisions-on-dx.md#tanstack-routers-origin-story).
|
|
46
|
-
|
|
47
26
|
## Why TanStack Router?
|
|
48
27
|
|
|
49
28
|
TanStack Router delivers on the same fundamental expectations as other routers that you’ve come to expect:
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tanstack/react-router",
|
|
3
|
-
"version": "1.133.
|
|
3
|
+
"version": "1.133.10",
|
|
4
4
|
"description": "Modern and scalable routing for React applications",
|
|
5
5
|
"author": "Tanner Linsley",
|
|
6
6
|
"license": "MIT",
|
|
@@ -79,8 +79,8 @@
|
|
|
79
79
|
"isbot": "^5.1.22",
|
|
80
80
|
"tiny-invariant": "^1.3.3",
|
|
81
81
|
"tiny-warning": "^1.0.3",
|
|
82
|
-
"@tanstack/
|
|
83
|
-
"@tanstack/
|
|
82
|
+
"@tanstack/router-core": "1.133.10",
|
|
83
|
+
"@tanstack/history": "1.133.3"
|
|
84
84
|
},
|
|
85
85
|
"devDependencies": {
|
|
86
86
|
"@testing-library/jest-dom": "^6.6.3",
|