From 6c180e8834c1dea8fdeee45fe0a263afb6a7020d Mon Sep 17 00:00:00 2001 From: Soheil Nikroo Date: Sun, 12 Jul 2026 16:16:50 +0330 Subject: [PATCH] docs(router): enhance router-context documentation with usage examples Added examples demonstrating the use of `Route.useRouteContext()` and `useRouteContext` hooks for accessing route context in components. This clarifies how to retrieve context from both the current route and parent routes, improving the documentation for better developer understanding. --- docs/router/guide/router-context.md | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/docs/router/guide/router-context.md b/docs/router/guide/router-context.md index 5fc4001010..fa9462da4b 100644 --- a/docs/router/guide/router-context.md +++ b/docs/router/guide/router-context.md @@ -181,8 +181,30 @@ export const Route = createFileRoute('/todos')({ component: Todos, loader: ({ context }) => fetchTodosByUserId(context.user.id), }) + +function Todos() { + const { user } = Route.useRouteContext() + + return
Todos for {user.id}
+} +``` + +`Route.useRouteContext()` is bound to the route's `Route` object, so TypeScript keeps the context narrowed to everything available at that route — including values merged from parent routes and anything returned from `beforeLoad`. Use it in components rendered within this route's match, such as the route component or other components defined in the same route file. + +To read context from another route — for example, a shared component that needs the root auth context — use the standalone [`useRouteContext`](../api/router/useRouteContextHook.md) hook with that route's id: + +```tsx +import { useRouteContext, rootRouteId } from '@tanstack/react-router' + +function UserBadge() { + const { user } = useRouteContext({ from: rootRouteId }) + + return {user.name} +} ``` +This is useful when a component needs context from a parent route instead of the nearest active match. + You can even inject data fetching and mutation implementations themselves! In fact, this is highly recommended 😜 Let's try this with a simple function to fetch some todos: