Read shared route state
A route's beforeLoad or loader places authenticated-user data in context, and a descendant component needs to display it.
TanStack · Hook
useRouteContext returns context for a specified current route. Use select to derive and return a narrower value.
useRouteContext reads the context belonging to the current route match. Pass the target route ID with from; optionally provide select to transform the context and receive only the selected value.
useRouteContext({ from: string, select?: (context: RouteContext) => TSelected })| Name | Type | Description |
|---|---|---|
opts.from | string | Required route ID used to identify the route context. |
opts.select | (context: RouteContext) => TSelected | Optional function receiving the route context and returning the value exposed by the hook. |
The current context for the current route, or the value returned by select when provided.
from is required and must identify the route whose context you want to read.import { useRouteContext } from '@tanstack/react-router'
export function UserBadge() {
const email = useRouteContext({
from: '/posts/$postId',
select: (context) => context.user.email,
})
return <span>{email}</span>
}Reads only the user's email from the context associated with the specified route.
A route's beforeLoad or loader places authenticated-user data in context, and a descendant component needs to display it.
A component needs one context property rather than the complete context object.
A route-aware component needs strongly identified context from a particular route ID.
It is a hook for reading the current route's context inside a component. The from option identifies the route context to use.
Follow-up: How can a component avoid consuming the whole context? Pass select and return only the needed property.
from is a required string containing the RouteID to match. It tells the hook which route's context should be returned.
Follow-up: What happens if the route ID is omitted? The documented hook signature requires the option, so provide an explicit route ID.
select is optional and receives the route context object. Its return value becomes the hook's result, allowing a component to consume a derived value such as a user ID.
Follow-up: What type does the selected result have? It is the selector's return type, represented in the documentation as TSelected.
Route.useRouteContextuseParamsuseSearchuseLoaderDatagetRouteApi