Loader data from parent routes when not using layout nesting

64 Views Asked by At

I am trying to access parent route loader data from child routes, when not using layout nesting.

Consider this set of routes:

account.invoices.tsx
account.invoices.due.tsx
account.invoices.paid.tsx

The "due" and "paid" routes use nested layouts, rendered via <Outlet />, and use a single data loader function in the parent account.invoices route. The loader data is accessible in both of the nested routes.

However, I frequently have slightly modified routing like this:

account.invoices.tsx
account.invoices_.due.tsx
account.invoices_.paid.tsx

This arrangement uses the trailing underscore so that the "due" and "paid" routes no longer use layout nesting.

This is a very common case for my Remix apps, whereby I have a parent route which has some overview UI, and then the child routes use the data that has already been loaded to render some other completely different views, and I specifically do NOT want layout nesting, i.e. not using <Outlet />.

The problem when doing this is that "account.invoices" and "account.invoices_" are different, and the child routes can no longer 'see' the loader data from the "account.invoices" route.

I can work around this by restructuring the routes, adding intermediate loader-only routes and an index route and so on, but this leads to somewhat confusing and more complex routes than maybe it should, something like this:

account.invoices._loader.tsx
account.invoices._loader._index.tsx
account.invoices._loader.due.tsx
account.invoices._loader.paid.tsx

Is this normal? Is there an idiomatic way to deal with this?

This is very similar to another of my questions on v1 routing, but this one more focused specifically on the difference in loader behaviour for routes like "account.invoices" vs "account.invoices_" with v2 routing.

Sharing data with Remix nested routes, while making parent route not accessible (Routing V2)

I added a code sandbox here:

https://codesandbox.io/p/devbox/dreamy-rhodes-xqm3hk

There are two scenarios in that sandbox, "good" and "bad", both accessible from the "/" page.

1

There are 1 best solutions below

1
Mr.unexpected On

Remix has a hook that you can use to access data from different routes. It is called useRouteLoaderData(param).