| name | tanstak-touter |
| description | Guide for using TanStack Router library. Use when working with React projects that need routing functionality. |
<@tanstack/react-router_api>
Always Apply: false - This rule should only be applied when relevant files are open
Always apply this rule in these files: src//*.ts, src//*.tsx
ActiveLinkOptions type
The ActiveLinkOptions type extends the LinkOptions type and contains additional options that can be used to describe how a link should be styled when it is active.
type ActiveLinkOptions = LinkOptions & {
activeProps?:
| React.AnchorHTMLAttributes<HTMLAnchorElement>
| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)
inactiveProps?:
| React.AnchorHTMLAttributes<HTMLAnchorElement>
| (() => React.AnchorHTMLAttributes<HTMLAnchorElement>)
}
ActiveLinkOptions properties
The ActiveLinkOptions object accepts/contains the following properties:
activeProps
React.AnchorHTMLAttributes<HTMLAnchorElement>
- Optional
- The props that will be applied to the anchor element when the link is active
inactiveProps
- Type:
React.AnchorHTMLAttributes<HTMLAnchorElement>
- Optional
- The props that will be applied to the anchor element when the link is inactive
AsyncRouteComponent type
The AsyncRouteComponent type is used to describe a code-split route component that can be preloaded using a component.preload() method.
type AsyncRouteComponent<TProps> = SyncRouteComponent<TProps> & {
preload?: () => Promise<void>
}
FileRoute class
[!CAUTION]
This class has been deprecated and will be removed in the next major version of TanStack Router.
Please use the createFileRoute function instead.
The 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.
FileRoute constructor
The FileRoute constructor accepts a single argument: the path of the file that the route will be generated for.
Constructor options
- Type:
string literal
- Required, but automatically inserted and updated by the
tsr generate and tsr watch commands.
- The full path of the file that the route will be generated from.
Constructor returns
- An instance of the
FileRoute class that can be used to create a route.
FileRoute methods
The FileRoute class implements the following method(s):
.createRoute method
The 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.
.createRoute options
- Type:
Omit<RouteOptions, 'getParentRoute' | 'path' | 'id'>
RouteOptions
- Optional
- 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.
.createRoute returns
A Route instance that can be used to configure the route to be inserted into the route-tree.
⚠️ Note: For tsr generate and tsr watch to work properly, the file route instance must be exported from the file using the Route identifier.
Examples
import { FileRoute } from '@tanstack/react-router'
export const Route = new FileRoute('/').createRoute({
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = Route.useLoaderData()
return <div>{data}</div>
}
LinkOptions type
The LinkOptions type extends the NavigateOptions type and contains additional options that can be used by TanStack Router when handling actual anchor element attributes.
type LinkOptions = NavigateOptions & {
target?: HTMLAnchorElement['target']
activeOptions?: ActiveOptions
preload?: false | 'intent'
preloadDelay?: number
disabled?: boolean
}
LinkOptions properties
The LinkOptions object accepts/contains the following properties:
target
- Type:
HTMLAnchorElement['target']
- Optional
- The standard anchor tag target attribute
activeOptions
- Type:
ActiveOptions
- Optional
- The options that will be used to determine if the link is active
preload
- Type:
false | 'intent' | 'viewport' | 'render'
- Optional
- If set, the link's preloading strategy will be set to this value.
- See the Preloading guide for more information.
preloadDelay
- Type:
number
- Optional
- Delay intent preloading by this many milliseconds. If the intent exits before this delay, the preload will be cancelled.
disabled
- Type:
boolean
- Optional
- If true, will render the link without the href attribute
LinkProps type
The LinkProps type extends the ActiveLinkOptions and React.AnchorHTMLAttributes<HTMLAnchorElement> types and contains additional props specific to the Link component.
type LinkProps = ActiveLinkOptions &
Omit<React.AnchorHTMLAttributes<HTMLAnchorElement>, 'children'> & {
children?:
| React.ReactNode
| ((state: { isActive: boolean }) => React.ReactNode)
}
LinkProps properties
- All of the props from
ActiveLinkOptions
- All of the props from
React.AnchorHTMLAttributes<HTMLAnchorElement>
children
- Type:
React.ReactNode | ((state: { isActive: boolean }) => React.ReactNode)
- Optional
- 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.
MatchRouteOptions type
The MatchRouteOptions type is used to describe the options that can be used when matching a route.
interface MatchRouteOptions {
pending?: boolean
caseSensitive?: boolean
includeSearch?: boolean
fuzzy?: boolean
}
MatchRouteOptions properties
The MatchRouteOptions type has the following properties:
pending property
- Type:
boolean
- Optional
- If
true, will match against pending location instead of the current location
caseSensitive property (deprecated)
- Type:
boolean
- Optional
- If
true, will match against the current location with case sensitivity
- Declare case sensitivity in the route definition instead, or globally for all routes using the
caseSensitive option on the router
includeSearch property
- Type:
boolean
- Optional
- 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 }
fuzzy property
- Type:
boolean
- Optional
- If
true, will match against the current location using a fuzzy match. e.g. /posts will match for a current location of /posts/123
NavigateOptions type
The NavigateOptions type is used to describe the options that can be used when describing a navigation action in TanStack Router.
type NavigateOptions = ToOptions & {
replace?: boolean
resetScroll?: boolean
hashScrollIntoView?: boolean | ScrollIntoViewOptions
viewTransition?: boolean | ViewTransitionOptions
ignoreBlocker?: boolean
reloadDocument?: boolean
href?: string
}
NavigateOptions properties
The NavigateOptions object accepts the following properties:
replace
- Type:
boolean
- Optional
- Defaults to
false.
- If
true, the location will be committed to the browser history using history.replace instead of history.push.
resetScroll
- Type:
boolean
- Optional
- Defaults to
true so that the scroll position will be reset to 0,0 after the location is committed to the browser history.
- If
false, the scroll position will not be reset to 0,0 after the location is committed to history.
hashScrollIntoView
- Type:
boolean | ScrollIntoViewOptions
- Optional
- Defaults to
true so the element with an id matching the hash will be scrolled into view after the location is committed to history.
- If
false, the element with an id matching the hash will not be scrolled into view after the location is committed to history.
- If an object is provided, it will be passed to the
scrollIntoView method as options.
- See MDN for more information on
ScrollIntoViewOptions.
viewTransition
- Type:
boolean | ViewTransitionOptions
- Optional
- Defaults to
false.
- If
true, navigation will be called using document.startViewTransition().
- If
ViewTransitionOptions, 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.
- If the browser does not support this api, this option will be ignored.
- See MDN for more information on how this function works.
- See Google for more information on viewTransition types
ignoreBlocker
- Type:
boolean
- Optional
- Defaults to
false.
- If
true, navigation will ignore any blockers that might prevent it.
reloadDocument
- Type:
boolean
- Optional
- Defaults to
false.
- If
true, navigation to a route inside of router will trigger a full page load instead of the traditional SPA navigation.
href
NotFoundError
The NotFoundError type is used to represent a not-found error in TanStack Router.
export type NotFoundError = {
global?: boolean
data?: any
throw?: boolean
routeId?: string
headers?: HeadersInit
}
NotFoundError properties
The NotFoundError object accepts/contains the following properties:
global property (⚠️ deprecated, use routeId: rootRouteId instead)
- Type:
boolean
- Optional -
default: false
- 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().
data property
- Type:
any
- Optional
- Custom data that is passed into to
notFoundComponent when the not-found error is handled
throw property
- Type:
boolean
- Optional -
default: false
- 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.
routeId property
- Type:
string
- Optional
- 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.
headers property
- Type:
HeadersInit
- Optional
- HTTP headers to be included when the not-found error is handled on the server side.
NotFoundRoute class
[!CAUTION]
This class has been deprecated and will be removed in the next major version of TanStack Router.
Please use the notFoundComponent route option that is present during route configuration.
See the Not Found Errors guide for more information.
The 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.
Constructor options
The NotFoundRoute constructor accepts an object as its only argument.
Omit<
RouteOptions,
| 'path'
| 'id'
| 'getParentRoute'
| 'caseSensitive'
| 'parseParams'
| 'stringifyParams'
>
- RouteOptions
- Required
- The options that will be used to configure the not found route instance.
Examples
import { NotFoundRoute, createRouter } from '@tanstack/react-router'
import { Route as rootRoute } from './routes/__root'
import { routeTree } from './routeTree.gen'
const notFoundRoute = new NotFoundRoute({
getParentRoute: () => rootRoute,
component: () => <div>Not found!!!</div>,
})
const router = createRouter({
routeTree,
notFoundRoute,
})
ParsedHistoryState type
The ParsedHistoryState type represents a parsed state object. Additionally to HistoryState, it contains the index and the unique key of the route.
export type ParsedHistoryState = HistoryState & {
key?: string
__TSR_key?: string
__TSR_index: number
}
ParsedLocation type
The 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.
interface ParsedLocation {
href: string
pathname: string
search: TFullSearchSchema
searchStr: string
state: ParsedHistoryState
hash: string
maskedLocation?: ParsedLocation
unmaskOnReload?: boolean
}
Redirect type
The Redirect type is used to represent a redirect action in TanStack Router.
export type Redirect = {
statusCode?: number
throw?: any
headers?: HeadersInit
} & NavigateOptions
Redirect properties
The Redirect object accepts/contains the following properties:
statusCode property
- Type:
number
- Optional
- The HTTP status code to use when redirecting
throw property
- Type:
any
- Optional
- 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.
headers property
- Type:
HeadersInit
- Optional
- The HTTP headers to use when redirecting.
Navigation Properties
Since Redirect extends NavigateOptions, it also supports navigation properties:
to: Use for internal application routes (e.g., /dashboard, ../profile)
href: Use for external URLs (e.g., https://example.com, https://authprovider.com)
Important: For external URLs, always use the href property instead of to. The to property is designed for internal navigation within your application.
Register type
This 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.
export type Register = {
}
To 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:
Examples
const router = createRouter({
})
declare module '@tanstack/react-router' {
interface Register {
router: typeof router
}
}
RootRoute class
[!CAUTION]
This class has been deprecated and will be removed in the next major version of TanStack Router.
Please use the createRootRoute function instead.
The 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.
RootRoute constructor
The RootRoute constructor accepts an object as its only argument.
Constructor options
The options that will be used to configure the root route instance.
Omit<
RouteOptions,
| 'path'
| 'id'
| 'getParentRoute'
| 'caseSensitive'
| 'parseParams'
| 'stringifyParams'
>
Constructor returns
A new Route instance.
Examples
import { RootRoute, createRouter, Outlet } from '@tanstack/react-router'
const rootRoute = new RootRoute({
component: () => <Outlet />,
})
const routeTree = rootRoute.addChildren([
])
const router = createRouter({
routeTree,
})
RouteApi class
[!CAUTION]
This class has been deprecated and will be removed in the next major version of TanStack Router.
Please use the getRouteApi function instead.
The 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.
Constructor options
The RouteApi constructor accepts a single argument: the options that will be used to configure the RouteApi instance.
opts.routeId option
- Type:
string
- Required
- The route ID to which the
RouteApi instance will be bound
Constructor returns
- An instance of the
RouteApi that is pre-bound to the route ID that it was called with.
Examples
import { RouteApi } from '@tanstack/react-router'
const routeApi = new RouteApi({ id: '/posts' })
export function PostsPage() {
const posts = routeApi.useLoaderData()
}
RouteApi Type
The 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.
RouteApi properties and methods
The RouteApi has the following properties and methods:
useMatch method
useMatch<TSelected = TAllContext>(opts?: {
select?: (match: TAllContext) => TSelected
}): TSelected
- A type-safe version of the
useMatch hook that is pre-bound to the route ID that the RouteApi instance was created with.
- Options
opts.select
- Optional
(match: RouteMatch) => TSelected
- 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.
opts.structuralSharing
- Optional
boolean
- Configures whether structural sharing is enabled for the value returned by
select.
- See the Render Optimizations guide for more information.
- Returns
- If a
select function is provided, the return value of the select function.
- If no
select function is provided, the RouteMatch object or a loosened version of the RouteMatch object if opts.strict is false.
useRouteContext method
useRouteContext<TSelected = TAllContext>(opts?: {
select?: (search: TAllContext) => TSelected
}): TSelected
- A type-safe version of the
useRouteContext hook that is pre-bound to the route ID that the RouteApi instance was created with.
- Options
opts.select
- Optional
(match: RouteContext) => TSelected
- 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.
- Returns
- If a
select function is provided, the return value of the select function.
- If no
select function is provided, the RouteContext object or a loosened version of the RouteContext object if opts.strict is false.
useSearch method
useSearch<TSelected = TFullSearchSchema>(opts?: {
select?: (search: TFullSearchSchema) => TSelected
}): TSelected
- A type-safe version of the
useSearch hook that is pre-bound to the route ID that the RouteApi instance was created with.
- Options
opts.select
- Optional
(match: TFullSearchSchema) => TSelected
- 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.
opts.structuralSharing
- Optional
boolean
- Configures whether structural sharing is enabled for the value returned by
select.
- See the Render Optimizations guide for more information.
- Returns
- If a
select function is provided, the return value of the select function.
- If no
select function is provided, the TFullSearchSchema object or a loosened version of the TFullSearchSchema object if opts.strict is false.
useParams method
useParams<TSelected = TAllParams>(opts?: {
select?: (params: TAllParams) => TSelected
}): TSelected
- A type-safe version of the
useParams hook that is pre-bound to the route ID that the RouteApi instance was created with.
- Options
opts.select
- Optional
(match: TAllParams) => TSelected
- 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.
opts.structuralSharing
- Optional
boolean
- Configures whether structural sharing is enabled for the value returned by
select.
- See the Render Optimizations guide for more information.
- Returns
- If a
select function is provided, the return value of the select function.
- If no
select function is provided, the TAllParams object or a loosened version of the TAllParams object if opts.strict is false.
useLoaderData method
useLoaderData<TSelected = TLoaderData>(opts?: {
select?: (search: TLoaderData) => TSelected
}): TSelected
- A type-safe version of the
useLoaderData hook that is pre-bound to the route ID that the RouteApi instance was created with.
- Options
opts.select
- Optional
(match: TLoaderData) => TSelected
- 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.
opts.structuralSharing
- Optional
boolean
- Configures whether structural sharing is enabled for the value returned by
select.
- See the Render Optimizations guide for more information.
- Returns
- If a
select function is provided, the return value of the select function.
- If no
select function is provided, the TLoaderData object or a loosened version of the TLoaderData object if opts.strict is false.
useLoaderDeps method
useLoaderDeps<TSelected = TLoaderDeps>(opts?: {
select?: (search: TLoaderDeps) => TSelected
}): TSelected
- A type-safe version of the
useLoaderDeps hook that is pre-bound to the route ID that the RouteApi instance was created with.
- Options
opts.select
- Optional
(match: TLoaderDeps) => TSelected
- If supplied, this function will be called with the route match and the return value will be returned from
useLoaderDeps.
opts.structuralSharing
- Optional
boolean
- Configures whether structural sharing is enabled for the value returned by
select.
- See the Render Optimizations guide for more information.
- Returns
- If a
select function is provided, the return value of the select function.
- If no
select function is provided, the TLoaderDeps object.
useNavigate method
useNavigate():
- A type-safe version of
useNavigate that is pre-bound to the route ID that the RouteApi instance was created with.
redirect method
redirect(opts?: RedirectOptions): Redirect
- A type-safe version of the
redirect function that is pre-bound to the route ID that the RouteApi instance was created with.
- The
from parameter is automatically set to the route ID, enabling type-safe relative redirects.
- Options
- All options from
redirect except from, which is automatically provided.
- Returns
- A
Redirect object that can be thrown from beforeLoad or loader callbacks.
Example
import { getRouteApi } from '@tanstack/react-router'
const routeApi = getRouteApi('/dashboard/settings')
export const Route = createFileRoute('/dashboard/settings')({
beforeLoad: ({ context }) => {
if (!context.user) {
throw routeApi.redirect({
to: '../login',
})
}
},
})
Route class
[!CAUTION]
This class has been deprecated and will be removed in the next major version of TanStack Router.
Please use the createRoute function instead.
The 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.
Route constructor
The Route constructor accepts an object as its only argument.
Constructor options
- Type:
RouteOptions
- Required
- The options that will be used to configure the route instance
Constructor returns
A new Route instance.
Examples
import { Route } from '@tanstack/react-router'
import { rootRoute } from './__root'
const indexRoute = new Route({
getParentRoute: () => rootRoute,
path: '/',
loader: () => {
return 'Hello World'
},
component: IndexComponent,
})
function IndexComponent() {
const data = indexRoute.useLoaderData()
return <div>{data}</div>
}
RouteMask type
The RouteMask type extends the ToOptions type and has other the necessary properties to create a route mask.
RouteMask properties
The RouteMask type accepts an object with the following properties:
...ToOptions
- Type:
ToOptions
- Required
- The options that will be used to configure the route mask
options.routeTree
- Type:
TRouteTree
- Required
- The route tree that this route mask will support
options.unmaskOnReload
- Type:
boolean
- Optional
- If
true, the route mask will be removed when the page is reloaded
RouteMatch type
The RouteMatch type represents a route match in TanStack Router.
interface RouteMatch {
id: string
routeId: string
pathname: string
params: Route['allParams']
status: 'pending' | 'success' | 'error' | 'redirected' | 'notFound'
isFetching: false | 'beforeLoad' | 'loader'
showPending: boolean
error: unknown
paramsError: unknown
searchError: unknown
updatedAt: number
loaderData?: Route['loaderData']
context: Route['allContext']
search: Route['fullSearchSchema']
fetchedAt: number
abortController: AbortController
cause: 'enter' | 'stay'
ssr?: boolean | 'data-only'
}
RouteOptions type
The RouteOptions type is used to describe the options that can be used when creating a route.
RouteOptions properties
The RouteOptions type accepts an object with the following properties:
getParentRoute method
- Type:
() => TParentRoute
- Required
- 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.
path property
- Type:
string
- Required, unless an
id is provided to configure the route as a pathless layout route
- The path segment that will be used to match the route.
id property
- Type:
string
- Optional, but required if a
path is not provided
- 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.
component property
- Type:
RouteComponent or LazyRouteComponent
- Optional - Defaults to
<Outlet />
- The content to be rendered when the route is matched.
errorComponent property
- Type:
RouteComponent or LazyRouteComponent
- Optional - Defaults to
routerOptions.defaultErrorComponent
- The content to be rendered when the route encounters an error.
pendingComponent property
- Type:
RouteComponent or LazyRouteComponent
- Optional - Defaults to
routerOptions.defaultPendingComponent
- The content to be rendered if and when the route is pending and has reached its pendingMs threshold.
notFoundComponent property
- Type:
NotFoundRouteComponent or LazyRouteComponent
- Optional - Defaults to
routerOptions.defaultNotFoundComponent
- The content to be rendered when the route is not found.
validateSearch method
- Type:
(rawSearchParams: unknown) => TSearchSchema
- Optional
- 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.
- 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.
search.middlewares property
- Type:
(({search: TSearchSchema, next: (newSearch: TSearchSchema) => TSearchSchema}) => TSearchSchema)[]
- Optional
- Search middlewares are functions that transform the search parameters when generating new links for a route or its descendants.
- 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.
parseParams method (⚠️ deprecated, use params.parse instead)
- Type:
(rawParams: Record<string, string>) => TParams
- Optional
- 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.
stringifyParams method (⚠️ deprecated, use params.stringify instead)
- Type:
(params: TParams) => Record<string, string>
- Required if
parseParams is provided
- 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.
params.parse method
- Type:
(rawParams: Record<string, string>) => TParams | false
- Optional
- 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 returns parsed params, its return value will be used as the route's params and the return type will be inferred into the rest of the router.
- Experimental: returning
false during incoming route matching skips this route and allows matching to continue to another candidate route.
params.stringify method
- Type:
(params: TParams) => Record<string, string>
- 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.
beforeLoad method
type beforeLoad = (
opts: RouteMatch & {
search: TFullSearchSchema
abortController: AbortController
preload: boolean
params: TAllParams
context: TParentContext
location: ParsedLocation
navigate: NavigateFn<AnyRoute> // @deprecated
buildLocation: BuildLocationFn<AnyRoute>
cause: 'enter' | 'stay'
},
) => Promise<TRouteContext> | TRouteContext | void
- Optional
ParsedLocation
- 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.
- 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.
- 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.
- 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.
🚧 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.
loader method
type loaderFn = (
opts: RouteMatch & {
abortController: AbortController
cause: 'preload' | 'enter' | 'stay'
context: TAllContext
deps: TLoaderDeps
location: ParsedLocation
params: TAllParams
preload: boolean
parentMatchPromise: Promise<MakeRouteMatchFromRoute<TParentRoute>>
navigate: NavigateFn<AnyRoute> // @deprecated
route: AnyRoute
},
) => Promise<TLoaderData> | TLoaderData | void
type loader =
| loaderFn
| {
handler: loaderFn
staleReloadMode?: 'background' | 'blocking'
}
- Optional
ParsedLocation
- 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.
- 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.
- 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.
- Deps must be returned by your
loaderDeps function in order to appear.
- Use the object form to configure loader-specific behavior like
staleReloadMode.
staleReloadMode: 'background' preserves stale-while-revalidate behavior for stale successful matches.
staleReloadMode: 'blocking' waits for the stale loader reload to complete before continuing.
🚧 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.
loaderDeps method
type loaderDeps = (opts: { search: TFullSearchSchema }) => Record<string, any>
- Optional
- 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.
- By default, path params are already used to uniquely identify a route match, so it's unnecessary to return these here.
- 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.
staleTime property
- Type:
number
- Optional
- Defaults to
routerOptions.defaultStaleTime, which defaults to 0
- 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.
preloadStaleTime property
- Type:
number
- Optional
- Defaults to
routerOptions.defaultPreloadStaleTime, which defaults to 30_000 ms (30 seconds)
- 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.
gcTime property
- Type:
number
- Optional
- Defaults to
routerOptions.defaultGcTime, which defaults to 30 minutes.
- 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.
shouldReload property
- Type:
boolean | ((args: LoaderArgs) => boolean)
- Optional
- If
false or returns false, the route match's loader data will not be reloaded on subsequent matches.
- If
true or returns true, the route match's loader data will be reloaded on subsequent matches.
- If
undefined or returns undefined, the route match's loader data will adhere to the default stale-while-revalidate behavior.
caseSensitive property
- Type:
boolean
- Optional
- If
true, this route will be matched as case-sensitive.
wrapInSuspense property
- Type:
boolean
- Optional
- 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.
pendingMs property
- Type:
number
- Optional
- Defaults to
routerOptions.defaultPendingMs, which defaults to 1000
- The threshold in milliseconds that a route must be pending before its
pendingComponent is shown.
pendingMinMs property
- Type:
number
- Optional
- Defaults to
routerOptions.defaultPendingMinMs which defaults to 500
- 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.
preloadMaxAge property
- Type:
number
- Optional
- Defaults to
30_000 ms (30 seconds)
- 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.
preSearchFilters property (⚠️ deprecated, use search.middlewares instead)
- Type:
((search: TFullSearchSchema) => TFullSearchSchema)[]
- Optional
- An array of functions that will be called when generating any new links to this route or its grandchildren.
- 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.
- 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.
postSearchFilters property (⚠️ deprecated, use search.middlewares instead)
- Type:
((search: TFullSearchSchema) => TFullSearchSchema)[]
- Optional
- An array of functions that will be called when generating any new links to this route or its grandchildren.
- 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.
- 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.
onError property
- Type:
(error: any) => void
- Optional
- A function that will be called when an error is thrown during a navigation or preload event.
- If this function throws a
redirect, then the router will process and apply the redirect immediately.
onEnter property
- Type:
(match: RouteMatch) => void
- Optional
- A function that will be called when a route is matched and loaded after not being matched in the previous location.
onStay property
- Type:
(match: RouteMatch) => void
- Optional
- A function that will be called when a route is matched and loaded after being matched in the previous location.
onLeave property
- Type:
(match: RouteMatch) => void
- Optional
- A function that will be called when a route is no longer matched after being matched in the previous location.
onCatch property
- Type:
(error: Error, errorInfo: ErrorInfo) => void
- Optional - Defaults to
routerOptions.defaultOnCatch
- A function that will be called when errors are caught when the route encounters an error.
remountDeps method
type remountDeps = (opts: RemountDepsOptions) => any
interface RemountDepsOptions<
in out TRouteId,
in out TFullSearchSchema,
in out TAllParams,
in out TLoaderDeps,
> {
routeId: TRouteId
search: TFullSearchSchema
params: TAllParams
loaderDeps: TLoaderDeps
}
- Optional
- 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.
- The return value needs to be JSON serializable.
- By default, a route component will not be remounted if it stays active after a navigation.
Example:
If you want to configure to remount a route component upon params change, use:
remountDeps: ({ params }) => params
headers method
type headers = (opts: {
matches: Array<RouteMatch>
match: RouteMatch
params: TAllParams
loaderData?: TLoaderData
}) => Promise<Record<string, string>> | Record<string, string>
- Optional
- 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.
head method
type head = (ctx: {
matches: Array<RouteMatch>
match: RouteMatch
params: TAllParams
loaderData?: TLoaderData
}) =>
| Promise<{
links?: RouteMatch['links']
scripts?: RouteMatch['headScripts']
meta?: RouteMatch['meta']
styles?: RouteMatch['styles']
}>
| {
links?: RouteMatch['links']
scripts?: RouteMatch['headScripts']
meta?: RouteMatch['meta']
styles?: RouteMatch['styles']
}
- Optional
- 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.
scripts method
type scripts = (ctx: {
matches: Array<RouteMatch>
match: RouteMatch
params: TAllParams
loaderData?: TLoaderData
}) => Promise<RouteMatch['scripts']> | RouteMatch['scripts']
- Optional
- A shorthand helper to return only
<script> elements. Equivalent to returning the scripts field from the head method.
codeSplitGroupings property
- Type:
Array<Array<'loader' | 'component' | 'pendingComponent' | 'notFoundComponent' | 'errorComponent'>>
- Optional
- 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.
Route type
The Route type is used to describe a route instance.
Route properties and methods
An instance of the Route has the following properties and methods:
.addChildren method
- Type:
(children: Route[]) => this
- Adds child routes to the route instance and returns the route instance (but with updated types to reflect the new children).
.update method
- Type:
(options: Partial<UpdatableRouteOptions>) => this
- Updates the route instance with new options and returns the route instance (but with updated types to reflect the new options).
- In some circumstances, it can be useful to update a route instance's options after it has been created to avoid circular type references.
- ...
RouteApi methods
.lazy method
- Type:
(lazyImporter: () => Promise<Partial<UpdatableRouteOptions>>) => this
- 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.
.redirect method
- Type:
(opts?: RedirectOptions) => Redirect
- A type-safe version of the
redirect function that is pre-bound to the route's path.
- The
from parameter is automatically set to the route's fullPath, enabling type-safe relative redirects.
- See
RouteApi.redirect for more details.
Example
import { createFileRoute } from '@tanstack/react-router'
export const Route = createFileRoute('/dashboard/settings')({
beforeLoad: ({ context }) => {
if (!context.user) {
throw Route.redirect({
to: '../login',
})
}
},
})
...RouteApi methods
- All of the methods from
RouteApi are available.
Router Class
[!CAUTION]
This class has been deprecated and will be removed in the next major version of TanStack Router.
Please use the createRouter function instead.
The Router class is used to instantiate a new router instance.
Router constructor
The Router constructor accepts a single argument: the options that will be used to configure the router instance.
Constructor options
- Type:
RouterOptions
- Required
- The options that will be used to configure the router instance.
Constructor returns
Examples
import { Router, RouterProvider } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = new Router({
routeTree,
defaultPreload: 'intent',
})
export default function App() {
return <RouterProvider router={router} />
}
RouterEvents type
The 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.
type RouterEvents = {
onBeforeNavigate: {
type: 'onBeforeNavigate'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onBeforeLoad: {
type: 'onBeforeLoad'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onLoad: {
type: 'onLoad'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onResolved: {
type: 'onResolved'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onBeforeRouteMount: {
type: 'onBeforeRouteMount'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
onInjectedHtml: {
type: 'onInjectedHtml'
}
onRendered: {
type: 'onRendered'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}
}
RouterEvents properties
Once an event is emitted, the following properties will be present on the event payload.
type property
- Type:
onBeforeNavigate | onBeforeLoad | onLoad | onBeforeRouteMount | onResolved | onRendered | onInjectedHtml
- The type of the event
- This is useful for discriminating between events in a listener function.
fromLocation property
- Type:
ParsedLocation
- The location that the router is transitioning from.
toLocation property
- Type:
ParsedLocation
- The location that the router is transitioning to.
pathChanged property
- Type:
boolean
true if the path has changed between the fromLocation and toLocation.
hrefChanged property
- Type:
boolean
true if the href has changed between the fromLocation and toLocation.
hashChanged property
- Type:
boolean
true if the hash has changed between the fromLocation and toLocation.
Example
import { createRouter } from '@tanstack/react-router'
import { routeTree } from './routeTree.gen'
const router = createRouter({ routeTree })
const unsub = router.subscribe('onResolved', (evt) => {
})
RouterOptions
The RouterOptions type contains all of the options that can be used to configure a router instance.
RouterOptions properties
The RouterOptions type accepts an object with the following properties and methods:
routeTree property
- Type:
AnyRoute
- Required
- The route tree that will be used to configure the router instance.
history property
- Type:
RouterHistory
- Optional
- The history object that will be used to manage the browser history. If not provided, a new
createBrowserHistory instance will be created and used.
stringifySearch method
- Type:
(search: Record<string, any>) => string
- Optional
- A function that will be used to stringify search params when generating links.
- Defaults to
defaultStringifySearch.
parseSearch method
- Type:
(search: string) => Record<string, any>
- Optional
- A function that will be used to parse search params when parsing the current location.
- Defaults to
defaultParseSearch.
search.strict property
- Type:
boolean
- Optional
- Defaults to
false
- Configures how unknown search params (= not returned by any
validateSearch) are treated.
- If
false, unknown search params will be kept.
- If
true, unknown search params will be removed.
defaultPreload property
- Type:
undefined | false | 'intent' | 'viewport' | 'render'
- Optional
- Defaults to
false
- If
false, routes will not be preloaded by default in any way.
- If
'intent', routes will be preloaded by default when the user hovers over a link or a touchstart event is detected on a <Link>.
- If
'viewport', routes will be preloaded by default when they are within the viewport of the browser.
- If
'render', routes will be preloaded by default as soon as they are rendered in the DOM.
defaultPreloadDelay property
- Type:
number
- Optional
- Defaults to
50
- The delay in milliseconds that a route must be hovered over or touched before it is preloaded.
defaultComponent property
- Type:
RouteComponent
- Optional
- Defaults to
Outlet
- The default
component a route should use if no component is provided.
defaultErrorComponent property
- Type:
RouteComponent
- Optional
- Defaults to
ErrorComponent
- The default
errorComponent a route should use if no error component is provided.
defaultNotFoundComponent property
- Type:
NotFoundRouteComponent
- Optional
- Defaults to
NotFound
- The default
notFoundComponent a route should use if no notFound component is provided.
defaultPendingComponent property
- Type:
RouteComponent
- Optional
- The default
pendingComponent a route should use if no pending component is provided.
defaultPendingMs property
- Type:
number
- Optional
- Defaults to
1000
- The default
pendingMs a route should use if no pendingMs is provided.
defaultPendingMinMs property
- Type:
number
- Optional
- Defaults to
500
- The default
pendingMinMs a route should use if no pendingMinMs is provided.
defaultStaleTime property
- Type:
number
- Optional
- Defaults to
0
- The default
staleTime a route should use if no staleTime is provided.
defaultStaleReloadMode property
- Type:
'background' | 'blocking'
- Optional
- Defaults to
'background'
- Controls how stale successful loader data is revalidated by default.
'background' preserves stale-while-revalidate behavior.
'blocking' waits for the stale loader reload to finish before navigation resolves.
defaultPreloadStaleTime property
- Type:
number
- Optional
- Defaults to
30_000 ms (30 seconds)
- The default
preloadStaleTime a route should use if no preloadStaleTime is provided.
defaultPreloadGcTime property
- Type:
number
- Optional
- Defaults to
routerOptions.defaultGcTime, which defaults to 30 minutes.
- The default
preloadGcTime a route should use if no preloadGcTime is provided.
defaultGcTime property
- Type:
number
- Optional
- Defaults to 30 minutes.
- The default
gcTime a route should use if no gcTime is provided.
defaultOnCatch property
- Type:
(error: Error, errorInfo: ErrorInfo) => void
- Optional
- The default
onCatch handler for errors caught by the Router ErrorBoundary
disableGlobalCatchBoundary property
- Type:
boolean
- Optional
- Defaults to
false
- 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.
- Useful for testing tools, error reporting services, and debugging scenarios.
protocolAllowlist property
- Type:
Array<string>
- Optional
- Defaults to
DEFAULT_PROTOCOL_ALLOWLIST which includes:
- Web navigation:
http:, https:
- Common browser-safe actions:
mailto:, tel:
- An array of URL protocols that are allowed in links, redirects, and navigation. Absolute URLs with protocols not in this list are rejected to prevent security vulnerabilities like XSS attacks.
- This check is applied across router navigation APIs, including:
<Link to="...">
navigate({ to: ... }) and navigate({ href: ... })
redirect({ to: ... }) and redirect({ href: ... })
- Protocol entries must match
URL.protocol format (lowercase with a trailing :), for example blob: or data:. If you configure protocolAllowlist: ['blob'] (without :), links using blob: will still be blocked.
Example
import {
createRouter,
DEFAULT_PROTOCOL_ALLOWLIST,
} from '@tanstack/react-router'
const router = createRouter({
routeTree,
protocolAllowlist: ['https:', 'mailto:'],
})
const router = createRouter({
routeTree,
protocolAllowlist: [...DEFAULT_PROTOCOL_ALLOWLIST, 'ftp:'],
})
defaultViewTransition property
- Type:
boolean | ViewTransitionOptions
- Optional
- If
true, route navigations will be called using document.startViewTransition().
- If
ViewTransitionOptions, 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.
- If the browser does not support this api, this option will be ignored.
- See MDN for more information on how this function works.
- See Google for more information on viewTransition types
defaultHashScrollIntoView property
- Type:
boolean | ScrollIntoViewOptions
- Optional
- Defaults to
true so the element with an id matching the hash will be scrolled into view after the location is committed to history.
- If
false, the element with an id matching the hash will not be scrolled into view after the location is committed to history.
- If an object is provided, it will be passed to the
scrollIntoView method as options.
- See MDN for more information on
ScrollIntoViewOptions.
caseSensitive property
- Type:
boolean
- Optional
- Defaults to
false
- If
true, all routes will be matched as case-sensitive.
basepath property
- Type:
string
- Optional
- Defaults to
/
- The basepath for the entire router. This is useful for mounting a router instance at a subpath.
rewrite property
- Type:
LocationRewrite
- Optional
- Configures bidirectional URL transformation between the browser URL and the router's internal URL.
- See the URL Rewrites guide for detailed usage and patterns.
The LocationRewrite type has the following shape:
type LocationRewrite = {
input?: LocationRewriteFunction
output?: LocationRewriteFunction
}
type LocationRewriteFunction = (opts: { url: URL }) => undefined | string | URL
input: Transforms the URL before the router interprets it (browser → router)
output: Transforms the URL before it's written to browser history (router → browser)
Example
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
routeTree,
rewrite: {
input: ({ url }) => {
if (url.pathname.startsWith('/en')) {
url.pathname = url.pathname.replace(/^\/en/, '') || '/'
}
return url
},
output: ({ url }) => {
url.pathname = `/en${url.pathname === '/' ? '' : url.pathname}`
return url
},
},
})
When both basepath and rewrite are configured, they are automatically composed. The basepath rewrite runs first on input (stripping the basepath) and last on output (adding it back).
context property
- Type:
any
- Optional or required if the root route was created with
createRootRouteWithContext().
- 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.
dehydrate method
- Type:
() => TDehydrated
- Optional
- 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.
hydrate method
- Type:
(dehydrated: TDehydrated) => void
- Optional
- 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.
routeMasks property
- Type:
RouteMask[]
- Optional
- 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.
unmaskOnReload property
- Type:
boolean
- Optional
- Defaults to
false
- 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 unmaskOnReload on the mask, or on a per-navigation basis by setting mask.unmaskOnReload in NavigateOptions.
Wrap property
- Type:
React.Component
- Optional
- 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.
Example
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
Wrap: ({ children }) => {
return <MyContext.Provider value={myContext}>{children}</MyContext>
},
})
InnerWrap property
- Type:
React.Component
- Optional
- 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.
Example
import { createRouter } from '@tanstack/react-router'
const router = createRouter({
InnerWrap: ({ children }) => {
const routerState = useRouterState()
return (
<MyContext.Provider value={myContext}>
{children}
</MyContext>
)
},
})
notFoundMode property
- Type:
'root' | 'fuzzy'
- Optional
- Defaults to
'fuzzy'
- 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 for more information.
notFoundRoute property
- Deprecated
- Type:
NotFoundRoute
- Optional
- 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.
trailingSlash property
- Type:
'always' | 'never' | 'preserve'
- Optional
- Defaults to
never
- 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.
pathParamsAllowedCharacters property
- Type:
Array<';' | ':' | '@' | '&' | '=' | '+' | '$' | ','>
- Optional
- Configures which URI characters are allowed in path params that would ordinarily be escaped by encodeURIComponent.
defaultStructuralSharing property
- Type:
boolean
- Optional
- Defaults to
false
- Configures whether structural sharing is enabled by default for fine-grained selectors.
- See the Render Optimizations guide for more information.
defaultRemountDeps property
type defaultRemountDeps = (opts: RemountDepsOptions) => any
interface RemountDepsOptions<
in out TRouteId,
in out TFullSearchSchema,
in out TAllParams,
in out TLoaderDeps,
> {
routeId: TRouteId
search: TFullSearchSchema
params: TAllParams
loaderDeps: TLoaderDeps
}
- Optional
- 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.
- The return value needs to be JSON serializable.
- By default, a route component will not be remounted if it stays active after a navigation
Example:
If you want to configure to remount all route components upon params change, use:
remountDeps: ({ params }) => params
RouterState type
The 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.
type RouterState = {
status: 'pending' | 'idle'
isLoading: boolean
isTransitioning: boolean
matches: Array<RouteMatch>
location: ParsedLocation
resolvedLocation: ParsedLocation
}
RouterState properties
The RouterState type contains all of the properties that are available on the router state.
status property
- Type:
'pending' | 'idle'
- 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.
isLoading property
- Type:
boolean
true if the router is currently loading a route or waiting for a route to finish loading.
isTransitioning property
- Type:
boolean
true if the router is currently transitioning to a new route.
matches property
- Type:
Array<RouteMatch>
- An array of all of the route matches that have been resolved and are currently active.
location property
- Type:
ParsedLocation
- The latest location that the router has parsed from the browser history. This location may not be resolved and loaded yet.
resolvedLocation property
- Type:
ParsedLocation
- The location that the router has resolved and loaded.
Router type
The Router type is used to describe a router instance.
Router properties and methods
An instance of the Router has the following properties and methods:
.update method
- Type:
(newOptions: RouterOptions) => void
- Updates the router instance with new options.
state property
⚠️⚠️⚠️ 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 hook.
.subscribe method
- Type:
(eventType: TType, fn: ListenerFn<RouterEvents[TType]>) => () => void
- Subscribes to a
RouterEvent.
- Returns a function that can be used to unsubscribe from the event.
- The listener will be called with the event payload whenever that event is emitted.
- See the Router Events guide for lifecycle ordering and usage patterns.
.matchRoutes method
- Type:
(pathname: string, locationSearch?: Record<string, any>, opts?: { throwOnError?: boolean; }) => RouteMatch[]
- Matches a pathname and search params against the router's route tree and returns an array of route matches.
- 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).
.cancelMatch method
- Type:
(matchId: string) => void
- Cancels a route match that is currently pending by calling
match.abortController.abort().
.cancelMatches method
- Type:
() => void
- Cancels all route matches that are currently pending by calling
match.abortController.abort() on each one.
.buildLocation method
Builds a new parsed location object that can be used later to navigate to a new location.
- Type:
(opts: BuildNextOptions) => ParsedLocation
- Properties
from
- Type:
string
- Optional
- The path to navigate from. If not provided, the current path will be used.
to
- Type:
string | number | null
- Optional
- The path to navigate to. If
null, the current path will be used.
params
- Type:
true | Updater<unknown>
- Optional
- 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.
search
- Type:
true | Updater<unknown>
- Optional
- 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.
hash
- Type:
true | Updater<string>
- Optional
- 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.
state
- Type:
true | NonNullableUpdater<ParsedHistoryState, HistoryState>
- Optional
- 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.
mask
- Type:
object
- Optional
- Contains all of the same BuildNextOptions, with the addition of
unmaskOnReload.
unmaskOnReload
- Type:
boolean
- Optional
- If
true, the route mask will be removed when the page is reloaded. This can be overridden on a per-navigation basis by setting mask.unmaskOnReload in NavigateOptions.
.commitLocation method
Commits a new location object to the browser history.
.navigate method
Navigates to a new location.
.invalidate method
Invalidates route matches by forcing their beforeLoad and load functions to be called again.
- Type:
(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean, sync?: boolean, forcePending?: boolean }) => Promise<void>
- 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.
- if
filter is not supplied, all matches will be invalidated
- if
filter is supplied, only matches for which filter returns true will be invalidated.
- if
sync is true, the promise returned by this function will only resolve once all loaders have finished.
- if
forcePending is true, the invalidated matches will be put into 'pending' state regardless whether they are in 'error' state or not.
- You might also want to invalidate the Router if you imperatively
reset the router's CatchBoundary to trigger loaders again.
.clearCache method
Remove cached route matches.
- Type:
(opts?: {filter?: (d: MakeRouteMatchUnion<TRouter>) => boolean}) => void
- if
filter is not supplied, all cached matches will be removed
- if
filter is supplied, only matches for which filter returns true will be removed.
.load method
Loads all of the currently matched route matches and resolves when they are all loaded and ready to be rendered.
⚠️⚠️⚠️ router.load() respects route.staleTime: fresh matches stay fresh, but stale matches are revalidated even if their loader key did not change. If you need to forcefully reload all active matches regardless of freshness, use router.invalidate() instead.
- Type:
(opts?: {sync?: boolean}) => Promise<void>
- if
sync is true, the promise returned by this function will only resolve once all loaders have finished.
- 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.
.preloadRoute method
Preloads all of the matches that match the provided NavigateOptions.
⚠️⚠️⚠️ Preloaded route matches are not stored long-term in the router state. They are only stored until the next attempted navigation action.
- Type:
(opts?: NavigateOptions) => Promise<RouteMatch[]>
- Properties
opts
- Type:
NavigateOptions
- Optional, defaults to the current location.
- The options that will be used to determine which route matches to preload.
- Returns
- A promise that resolves with an array of all of the route matches that were preloaded.
.loadRouteChunk method
Loads the JS chunk of the route.
- Type:
(route: AnyRoute) => Promise<void>
.matchRoute method
Matches 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.
- Type:
(dest: ToOptions, matchOpts?: MatchRouteOptions) => RouteMatch['params'] | false
- Properties
dest
- Type:
ToOptions
- Required
- The destination to match against.
matchOpts
- Type:
MatchRouteOptions
- Optional
- Options that will be used to match the destination.
- Returns
- A route match's params if a match was found.
false if no match was found.
.dehydrate method
Dehydrates the router's critical state into a serializable object that can be sent to the client in an initial request.
- Type:
() => DehydratedRouter
- Returns
- A serializable object that contains the router's critical state.
.hydrate method
Hydrates the router's critical state from a serializable object that was sent from the server in an initial request.
- Type:
(dehydrated: DehydratedRouter) => void
- Properties
dehydrated
- Type:
DehydratedRouter
- Required
- The dehydrated router state that was sent from the server.
ToMaskOptions type
The ToMaskOptions type includes the same destination fields as ToOptions, excluding mask, and adds options specific to route masking.
type ToMaskOptions = {
from?: ValidRoutePath | string
to?: ValidRoutePath | string
hash?: true | string | ((prev?: string) => string)
state?: true | HistoryState | ((prev: HistoryState) => HistoryState)
} & SearchParamOptions &
PathParamOptions & {
unmaskOnReload?: boolean
}
ToOptions type
The ToOptions type contains several properties that can be used to describe a router destination, including mask for route masking.
type ToOptions = {
from?: ValidRoutePath | string
to?: ValidRoutePath | string
hash?: true | string | ((prev?: string) => string)
state?: true | HistoryState | ((prev: HistoryState) => HistoryState)
} & SearchParamOptions &
PathParamOptions &
MaskOptions
type SearchParamOptions = {
search?: true | TToSearch | ((prev: TFromSearch) => TToSearch)
}
type PathParamOptions = {
params?:
| true
| Record<string, TPathParam>
| ((prev: TFromParams) => TToParams)
}
type MaskOptions = {
mask?: ToMaskOptions<TRouter, TMaskFrom, TMaskTo>
}
UseMatchRouteOptions type
The UseMatchRouteOptions type extends the ToOptions type and describes additional options available when using the useMatchRoute hook.
export type UseMatchRouteOptions = ToOptions & MatchRouteOptions
ViewTransitionOptions type
The ViewTransitionOptions type is used to define a
viewTransition type.
interface ViewTransitionOptions {
types:
| Array<string>
| ((locationChangeInfo: {
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
hashChanged: boolean
}) => Array<string> | false)
}
ViewTransitionOptions properties
The ViewTransitionOptions type accepts an object with a single property:
types property
- Type:
Array<string> | ((locationChangeInfo: { fromLocation?: ParsedLocation toLocation: ParsedLocation pathChanged: boolean hrefChanged: boolean hashChanged: boolean }) => (Array<string> | false))
- Required
- Either one of:
- An array of strings that will be passed to the
document.startViewTransition({update, types}) call
- A function that accepts
locationChangeInfo object and returns either:
- An array of strings that will be passed to the
document.startViewTransition({update, types}) call
- or
false to skip the view transition
Await component
The Await component is a component that suspends until the provided promise is resolved or rejected.
This is only necessary for React 18.
If you are using React 19, you can use the use() hook instead.
Await props
The Await component accepts the following props:
props.promise prop
- Type:
Promise<T>
- Required
- The promise to await.
props.children prop
- Type:
(result: T) => React.ReactNode
- Required
- A function that will be called with the resolved value of the promise.
Await returns
- Throws an error if the promise is rejected.