T
TanStack15mo ago
deep-jade

Is there a hook to access router context ?

I followed the guide for React Context: https://tanstack.com/router/latest/docs/framework/react/guide/router-context#router-context I would like to access the context from a component like this:
const context = useRouterContext();
const context = useRouterContext();
But I didn't find a way to do it. Do you have any solution?
Router Context | TanStack Router React Docs
TanStack Router's router context is a very powerful tool that can be used for dependency injection among many other things. Aptly named, the router context is passed through the router and down through each matching route. At each route in the hierarchy, the context can be modified or added to. Here's a few ways you might use the router context...
3 Replies
deep-jade
deep-jadeOP15mo ago
If that hook does not exist, how can I create a custom one to achieve this behavior? It looks like I found the solution:
const useRouterContext = () => useRouteContext({ from: '__root__' });
const useRouterContext = () => useRouteContext({ from: '__root__' });
What do you think about this? Is it okay?
distinguished-silver
distinguished-silver15mo ago
don't use __root__ as a string, use rootRouteId since this particular string might change, but the exported symbol would be updated in this case aside from that, you could also use useRouteContext({strict: false})
deep-jade
deep-jadeOP15mo ago
Thanks for your clear response! I imagine that it could be useful for other users, so could we add this hook to the library? Hello! When I use the hook useRouteContext({strict: false}), the typing tells me that every property of the context can be null So I used useRouteContext({ from: Root.id }) with Root corresponding to root route

Did you find this page helpful?