Typed dependency context
A router needs shared services such as a QueryClient available to route loaders and child routes.
TanStack · Function
Creates a typed root-route factory whose context contract must be satisfied when the router is created. Use it to make router context available with consistent types across the route tree.
Call createRootRouteWithContext with the router-context type, then call the returned factory with root-route options. The resulting route tree carries that type contract, so createRouter must receive a context object satisfying it; the context remains available throughout the route tree.
createRootRouteWithContext<TRouterContext>()(routeOptions)| Name | Type | Description |
|---|---|---|
TRouterContext | generic type | The router context type that must be supplied when createRouter is called. It is optional but recommended. |
A factory function for creating a createRootRoute instance; it accepts the same argument as createRootRoute.
import { createRootRouteWithContext, createRouter } from '@tanstack/react-router'
interface RouterContext {
queryClient: QueryClient
}
declare const QueryClient: new () => unknown
const rootRoute = createRootRouteWithContext<RouterContext>()({
component: () => null,
})
const routeTree = rootRoute.addChildren([])
const queryClient = new QueryClient()
const router = createRouter({
routeTree,
context: { queryClient },
})
void routerThe typed root route requires the router to provide a matching context object.
A router needs shared services such as a QueryClient available to route loaders and child routes.
Authentication state or other application-wide values must be passed into the router with compile-time checking.
A route tree should expose one consistent context contract to all descendant routes.
It creates a root-route factory whose generic context type becomes a requirement when the router is instantiated. Supplying the generic gives the route tree and its child routes a consistent context contract.
Follow-up: What happens if the router omits a required context property? TypeScript reports that the router configuration does not satisfy the context contract.
The first call supplies the context type, and the returned factory is then called with the same root-route options accepted by createRootRoute. This produces the root route used to build the route tree.
Follow-up: Why are there two calls? The first configures the factory's generic type; the second creates the route instance.
The context is supplied in createRouter through its context option. Once the root route establishes the type, that object must fulfill the declared contract.
Follow-up: Can child routes use the context? Yes; the typed context is available throughout the route tree.
createRootRoutecreateRouterRouter ContextrootRoute