T
TanStack2w ago
vicious-gold

Modify Router Context from deep in React-land

Hi everyone! I'm trying to figure out the idiomatic way to modify the Router Context deep within the component tree. At the root, I know we can pass values to the RouterProvider via the context option, but what's the recommended approach if I want to update context further down? For example, I have a section of my app wrapped in a Provider. I can access its value in React via use, but I don't see a straightforward way to sync that with the Router Context to be able to access it in, e.g., loader. I currently have this within my provider:
const router = useRouter();

useEffect(() => {
if (selectedWorkspace) {
router.update({
context: { ...router.options.context, workspace: selectedWorkspace },
});
router.invalidate();
}
}, [selectedWorkspace, router]);
const router = useRouter();

useEffect(() => {
if (selectedWorkspace) {
router.update({
context: { ...router.options.context, workspace: selectedWorkspace },
});
router.invalidate();
}
}, [selectedWorkspace, router]);
It works, but I'm wondering: is this the "right" way to do it?
1 Reply
stormy-gold
stormy-gold2w ago
you could hand a setState down to the component and feed that state into router context via <RouterProvider context={...} >

Did you find this page helpful?