Access route APIs from a separate component file
A component is located away from its route definition and needs typed loader data, params, search state, or context.
TanStack · Function
Creates a type-safe RouteApi bound to a route ID. Use it to access route hooks and APIs without importing the route object.
Call getRouteApi with a route ID literal to obtain a RouteApi instance tied to that route's registered types. Use the instance for type-safe route hooks and related APIs, especially when component code is separate from the route definition or code-split.
getRouteApi(routeId)| Name | Type | Description |
|---|---|---|
routeId | string literal | Required route ID to bind the returned RouteApi instance to. |
A RouteApi instance pre-bound to the supplied route ID.
import { getRouteApi } from '@tanstack/react-router'
const routeApi = getRouteApi('/posts')
export function PostsPage() {
const posts = routeApi.useLoaderData()
return <ul>{posts.map((post) => <li key={post.id}>{post.title}</li>)}</ul>
}Creates a route-bound API and uses its typed loader-data hook in a component that does not import the route object.
A component is located away from its route definition and needs typed loader data, params, search state, or context.
A route's UI is code-split and should avoid importing its route configuration.
Authentication or other route logic needs a typed redirect outside the route definition.
getRouteApi accepts a route ID string literal and returns a RouteApi instance bound to that ID. The instance exposes type-safe route APIs such as useParams, useSearch, useLoaderData, and useNavigate.
Follow-up: Why use it in a separate component file? It provides typed route access without importing the route configuration, helping avoid circular dependencies.
Pass the route ID to getRouteApi, then call the desired API on the returned object. For example, getRouteApi('/posts').useLoaderData() accesses loader data using the registered types for /posts.
Follow-up: How would you access route parameters instead? Call routeApi.useParams() on the instance created for that route ID.
The returned RouteApi is pre-bound to the supplied route ID. This binding supplies the corresponding registered route types to its supported hooks and APIs.
Follow-up: Can it help with redirects? Yes; its redirect API is route-bound, and the route ID is automatically used as the from value for type-safe relative redirects.
RouteApiuseParamsuseSearchuseRouteContextuseNavigateuseLoaderDatauseLoaderDepsredirect