TanStackT
TanStack4mo ago
1 reply
sad-indigo

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]);


It works, but I'm wondering: is this the "right" way to do it?
Was this page helpful?