Instruction file imported from vx4snow/sndvtfrontend (
.cursor/rules/tanstack-react-router_api.mdc). Copyright stays with the author.
description: TanStack Router: API globs: src//*.ts,src//*.tsx alwaysApply: false
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
createFileRoutefunction 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:
stringliteral - Required, but automatically inserted and updated by the
tsr generateandtsr watchcommands. - The full path of the file that the route will be generated from.
Constructor returns
- An instance of the
FileRouteclass 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
Routeclass, but with thegetParentRoute,path, andidoptions 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 generateandtsr watchto work properly, the file route instance must be exported from the file using theRouteidentifier.
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
isActiveboolean 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
- Type:
boolean - Optional
- If
true, will match against the current location with case sensitivity
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./postswill 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 usinghistory.replaceinstead ofhistory.push.
resetScroll
- Type:
boolean - Optional
- Defaults to
trueso 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
trueso 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
scrollIntoViewmethod as options. - See MDN for more information on
ScrollIntoViewOptions.
viewTransition
- Type:
boolean | ViewTransitionOptions - Optional
- Defaults to
false. - If
true, navigation will be called usingdocument.startViewTransition(). - If
ViewTransitionOptions, route navigations will be called usingdocument.startViewTransition({update, types})wheretypeswill be the strings array passed withViewTransitionOptions["types"]. If the browser does not support viewTransition types, the navigation will fall back to normaldocument.startTransition(), same as iftruewas 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
-
Type:
string -
Optional
-
This can be used instead of
toto navigate to a fully built href, e.g. pointing to an external target.
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
}
NotFoundError properties
The NotFoundError object accepts/contains the following properties:
data property
- Type:
any - Optional
- Custom data that is passed into to
notFoundComponentwhen the not-found error is handled
global property
- Type:
boolean - Optional -
default: false - If true, the not-found error will be handled by the
notFoundComponentof the root route instead of bubbling up from the route that threw it. This has the same behavior as importing the root route and callingRootRoute.notFound().
route 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.
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
throwingin a function might cause it to have a return type ofnever. In that case, you can usenotFound({ throw: true })to throw the not-found object instead of returning it.
NotFoundRoute class
[!CAUTION] This class has been deprecated and will be removed in the next major version of TanStack Router. Please use the
notFoundComponentroute 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.
- Type:
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,
})
// ... other code
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_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
throwingin a function might cause it to have a return type ofnever. In that case, you can useredirect({ throw: true })to throw the redirect object instead of returning it.
headers property
- Type:
HeadersInit - Optional
- The HTTP headers to use when redirecting.
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 = {
// router: [Your router type here]
}
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
createRootRoutefunction 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.
- Type:
Omit<
RouteOptions,
| 'path'
| 'id'
| 'getParentRoute'
| 'caseSensitive'
| 'parseParams'
| 'stringifyParams'
>
RouteOptions- Optional
Constructor returns
A new Route instance.
Examples
import { RootRoute, createRouter, Outlet } from '@tanstack/react-router'
const rootRoute = new RootRoute({
component: () => <Outlet />,
// ... root route options
})
const routeTree = rootRoute.addChildren([
// ... other routes
])
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
getRouteApifunction 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
RouteApiinstance will be bound
Constructor returns
- An instance of the
RouteApithat 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
useMatchhook that is pre-bound to the route ID that theRouteApiinstance 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
selectfunction is provided, the return value of theselectfunction. - If no
selectfunction is provided, theRouteMatchobject or a loosened version of theRouteMatchobject ifopts.strictisfalse.
- If a
useRouteContext method
useRouteContext<TSelected = TAllContext>(opts?: {
select?: (search: TAllContext) => TSelected
}): TSelected
- A type-safe version of the
useRouteContexthook that is pre-bound to the route ID that theRouteApiinstance 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
selectfunction is provided, the return value of theselectfunction. - If no
selectfunction is provided, theRouteContextobject or a loosened version of theRouteContextobject ifopts.strictisfalse.
- If a
useSearch method
useSearch<TSelected = TFullSearchSchema>(opts?: {
select?: (search: TFullSearchSchema) => TSelected
}): TSelected
- A type-safe version of the
useSearchhook that is pre-bound to the route ID that theRouteApiinstance 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
selectfunction is provided, the return value of theselectfunction. - If no
selectfunction is provided, theTFullSearchSchemaobject or a loosened version of theTFullSearchSchemaobject ifopts.strictisfalse.
- If a
useParams method
useParams<TSelected = TAllParams>(opts?: {
select?: (params: TAllParams) => TSelected
}): TSelected
- A type-safe version of the
useParamshook that is pre-bound to the route ID that theRouteApiinstance 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
selectfunction is provided, the return value of theselectfunction. - If no
selectfunction is provided, theTAllParamsobject or a loosened version of theTAllParamsobject ifopts.strictisfalse.
- If a
useLoaderData method
useLoaderData<TSelected = TLoaderData>(opts?: {
select?: (search: TLoaderData) => TSelected
}): TSelected
- A type-safe version of the
useLoaderDatahook that is pre-bound to the route ID that theRouteApiinstance 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
selectfunction is provided, the return value of theselectfunction. - If no
selectfunction is provided, theTLoaderDataobject or a loosened version of theTLoaderDataobject ifopts.strictisfalse.
- If a
useLoaderDeps method
useLoaderDeps<TSelected = TLoaderDeps>(opts?: {
select?: (search: TLoaderDeps) => TSelected
}): TSelected
- A type-safe version of the
useLoaderDepshook that is pre-bound to the route ID that theRouteApiinstance 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
selectfunction is provided, the return value of theselectfunction. - If no
selectfunction is provided, theTLoaderDepsobject.
- If a
useNavigate method
useNavigate(): // navigate function
- A type-safe version of
useNavigatethat is pre-bound to the route ID that theRouteApiinstance was created with.
Route class
[!CAUTION] This class has been deprecated and will be removed in the next major version of TanStack Router. Please use the
createRoutefunction 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'
isFetching: boolean
showPending: boolean
error: unknown
paramsError: unknown
searchError: unknown
updatedAt: number
loadPromise?: Promise<void>
loaderData?: Route['loaderData']
context: Route['allContext']
search: Route['fullSearchSchema']
fetchedAt: number
abortController: AbortController
cause: 'enter' | 'stay'
}
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
idis 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
pathis 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:
RouteComponentorLazyRouteComponent - Optional - Defaults to
<Outlet /> - The content to be rendered when the route is matched.
errorComponent property
- Type:
RouteComponentorLazyRouteComponent - Optional - Defaults to
routerOptions.defaultErrorComponent - The content to be rendered when the route encounters an error.
pendingComponent property
- Type:
RouteComponentorLazyRouteComponent - 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:
NotFoundRouteComponentorLazyRouteComponent - 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
SearchSchemaInputtype like this:(searchParams: TSearchSchemaInput & SearchSchemaInput) => TSearchSchema. If this tag is present,TSearchSchemaInputwill be used to type thesearchproperty of<Link />andnavigate()instead ofTSearchSchema. The difference betweenTSearchSchemaInputandTSearchSchemacan 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
parseParamsis 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 - 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.
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:
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
onErrorfunction. 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
pendingComponentwill 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
TRouteContextobject, that object will be merged into the route's context and be made available in theloaderand 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
redirectobject from this function.
🚧
opts.navigatehas been deprecated and will be removed in the next major release. Usethrow redirect({ to: '/somewhere' })instead. Read more about theredirectfunction here.
loader method
- Type:
type loader = (
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
- 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
onErrorfunction. 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
pendingComponentwill 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
TLoaderDataobject, that object will be stored on the route match until the route match is no longer active. It can be accessed using theuseLoaderDatahook in any component that is a child of the route match before another<Outlet />is rendered. - Deps must be returned by your
loaderDepsfunction in order to appear.
🚧
opts.navigatehas been deprecated and will be removed in the next major release. Usethrow redirect({ to: '/somewhere' })instead. Read more about theredirectfunction here.
loaderDeps method
- Type:
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'sdepsargument.
staleTime property
- Type:
number - Optional
- Defaults to
routerOptions.defaultStaleTime, which defaults to0 - 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 to30_000ms (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
staleTimeis 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
falseor returnsfalse, the route match's loader data will not be reloaded on subsequent matches. - If
trueor returnstrue, the route match's loader data will be reloaded on subsequent matches. - If
undefinedor returnsundefined, 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 to1000 - The threshold in milliseconds that a route must be pending before its
pendingComponentis shown.
pendingMinMs property
- Type:
number - Optional
- Defaults to
routerOptions.defaultPendingMinMswhich defaults to500 - 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_000ms (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
preprefix because it is called before the user-provided function that is passed tonavigate/Linketc 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
postprefix because it is called after the user-provided function that is passed tonavigate/Linketc 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:
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
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.
- ...
RouteApimethods
.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.
...RouteApi methods
- All of the methods from
RouteApiare available.
Router Class
[!CAUTION] This class has been deprecated and will be removed in the next major version of TanStack Router. Please use the
createRouterfunction 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
- An instance of the
Router.
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
}
onBeforeLoad: {
type: 'onBeforeLoad'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
}
onLoad: {
type: 'onLoad'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
}
onResolved: {
type: 'onResolved'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
}
onBeforeRouteMount: {
type: 'onBeforeRouteMount'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
pathChanged: boolean
hrefChanged: boolean
}
onInjectedHtml: {
type: 'onInjectedHtml'
promise: Promise<string>
}
onRendered: {
type: 'onRendered'
fromLocation?: ParsedLocation
toLocation: ParsedLocation
}
}
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 - 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 trueif the path has changed between thefromLocationandtoLocation.
hrefChanged property
- Type:
boolean trueif the href has changed between thefromLocationandtoLocation.
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
createBrowserHistoryinstance 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 atouchstartevent 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
componenta route should use if no component is provided.
defaultErrorComponent property
- Type:
RouteComponent - Optional
- Defaults to
ErrorComponent - The default
errorComponenta route should use if no error component is provided.
defaultNotFoundComponent property
- Type:
NotFoundRouteComponent - Optional
- Defaults to
NotFound - The default
notFoundComponenta route should use if no notFound component is provided.
defaultPendingComponent property
- Type:
RouteComponent - Optional
- The default
pendingComponenta route should use if no pending component is provided.
defaultPendingMs property
- Type:
number - Optional
- Defaults to
1000 - The default
pendingMsa route should use if no pendingMs is provided.
defaultPendingMinMs property
- Type:
number - Optional
- Defaults to
500 - The default
pendingMinMsa route should use if no pendingMinMs is provided.
defaultStaleTime property
- Type:
number - Optional
- Defaults to
0 - The default
staleTimea route should use if no staleTime is provided.
defaultPreloadStaleTime property
- Type:
number - Optional
- Defaults to
30_000ms (30 seconds) - The default
preloadStaleTimea route should use if no preloadStaleTime is provided.
defaultPreloadGcTime property
- Type:
number - Optional
- Defaults to
routerOptions.defaultGcTime, which defaults to 30 minutes. - The default
preloadGcTimea route should use if no preloadGcTime is provided.
defaultGcTime property
- Type:
number - Optional
- Defaults to 30 minutes.
- The default
gcTimea route should use if no gcTime is provided.
defaultOnCatch property
- Type:
(error: Error, errorInfo: ErrorInfo) => void - Optional
- The default
onCatchhandler for errors caught by the Router ErrorBoundary
defaultViewTransition property
- Type:
boolean | ViewTransitionOptions - Optional
- If
true, route navigations will be called usingdocument.startViewTransition(). - If
ViewTransitionOptions, route navigations will be called usingdocument.startViewTransition({update, types})wheretypeswill be the strings array passed withViewTransitionOptions["types"]. If the browser does not support viewTransition types, the navigation will fall back to normaldocument.startTransition(), same as iftruewas 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
trueso 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
scrollIntoViewmethod 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 then entire router. This is useful for mounting a router instance at a subpath.
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 theunmaskOnReloadoption on the mask, or on a per-navigation basis by setting theunmaskOnReloadoption in theNavigateoptions.
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
NotFoundRouteoption on the root route of the branch.
errorSerializer property
- Type: [
RouterErrorSerializer] - Optional
- The serializer object that will be used to determine how errors are serialized and deserialized between the server and the client.
errorSerializer.serialize method
- Type:
(err: unknown) => TSerializedError - This method is called to define how errors are serialized when they are stored in the router's dehydrated state.
errorSerializer.deserialize method
- Type:
(err: TSerializedError) => unknown - This method is called to define how errors are deserialized from the router's dehydrated state.
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:
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>
pendingMatches: 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 trueif the router is currently loading a route or waiting for a route to finish loading.
isTransitioning property
- Type:
boolean trueif 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.
pendingMatches property
- Type:
Array<RouteMatch> - An array of all of the route matches that are currently pending.
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
- Type:
RouterState - The current state of the router.
⚠️⚠️⚠️
router.stateis always up to date, but NOT REACTIVE. If you userouter.statein a component, the component will not re-render when the router state changes. To get a reactive version of the router state, use theuseRouterStatehook.
`
*Truncated - read the full file at https://github.com/vx4snow/sndvtfrontend/blob/7442c2c28504de203f39698bc18cde0e0e804522/.cursor/rules/tanstack-react-router_api.mdc