How to replicate React Router Outlet like utility for Next.js?

A module in my Next.js application has a sidebar. I want to navigate to those paths without re-fetching the same data (that belongs to the parent component) from the API. The routing system of Next.js is restricting me to achieve the same. Is there any way I can replicate react-router "Outlet" like utility in Next.js? Thanks!
7 Replies
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View
visshhhal
visshhhalOP3y ago
considering this hypothetical example, following is the folder structure: /users profile.tsx team.tsx billing.tsx And here's how I wish to render my pages: /user/profile /user/team /user/billing I need user info on all three pages But because of the file based routing system, I'm forced to call the API on all three pages, in addition to re-writing the same sidebar UI code (although that's been maintained in as a separate layout component, but still)
FluX
FluX3y ago
I just implemented this in my project the other day, for a dashboard where admins can manage users. My folder structure is as follows (using the app directory):
.
└── users/
├── [id]/
│ ├── transactions/
│ │ └── page.tsx
│ ├── settings/
│ │ └── page.tsx
│ ├── page.tsx
│ └── layout.tsx
└── page.tsx
.
└── users/
├── [id]/
│ ├── transactions/
│ │ └── page.tsx
│ ├── settings/
│ │ └── page.tsx
│ ├── page.tsx
│ └── layout.tsx
└── page.tsx
The layout under users/[id]/ has a static sidebar navigation component which takes the user ID as a prop, so that I can set the links. I get the user ID from the layouts params prop. As you can't pass props to pages inside a layout (or can you?) I fetch the user on every subpage. I'm not sure if this can be avoided
cje
cje3y ago
if you're using next-auth, you're not actually fetching the user multiple times it exists in context if one component has it, all others get it for free
FluX
FluX3y ago
I'm not using next-auth ^^
Develliot
Develliot3y ago
If you are using react query or swr then even if it calls the same get request it's cached and deduplicated so you don't have to worry about it too much. Or you can make your own context I think what outlet does is similar to what the new layout folders in app directory do. The app directory is all about server side though. Client side I guess all outlets are doing are rendering parents and passing the child route as children to the parent component. I would lean on parent components and children components that make their own queries + react query/swr cache to do this stuff client side. It's a different pattern for Next JS /pages routing but has the same effect of composability.
visshhhal
visshhhalOP3y ago
This works for me I'll check if we can pass props though Thanks!

Did you find this page helpful?