DEV Community

Tochukwu John
Tochukwu John

Posted on • Updated on

Sharing Layouts with NextJS 13 app dir

Hey there πŸ‘‹πŸ‘‹ my fellow NextJS devs πŸ’ͺ, so While I was working on my side project, I noticed something about the new NextJS 13 app dir. I was like since routes can share layouts, what if I could a share layout for certain routes without affecting the URL? πŸ€”. I was sure this wasn’t possible till I visited the docs and found an interesting section on route-groups πŸ˜‡πŸ˜Š.

So basically, this allows you to define multiple routes by wrapping a folder's name in parenthesis: (folderName) and as a result when you define a layout.js/tsx for this folder, all sub folders/routes would inherit and share the layout. 😲😲

More info here - Route Groups | Next.js

This is especially useful if you have several segments of your site that share similar layouts. Instead of repeating layouts everywhere πŸ€¦β€β™‚οΈ, you can make use of a route group instead.

To showcase this, I've gone ahead to create a demo-app, you can find the GitHub repo here: Github - Route Group

Inside the app folder
I added two route-groups

  • onboarding
  • authenticated

Each with it’s own routes
Routes

Inside the route-group folders, there is a layout.tsx file bearing the layout that would be shared by all the routes in the folder, which means components that are placed in the layout.tsx files are not re-rendered when navigating across pages.

Onboarding layout

From the code snippet above, the <Navigation/> component would not be re-rendered when navigating and would maintain its state when navigating.

To further prove this I added a <RouteProof /> component to the (authenticated) layout.

Authenticated layout

The <RouteProof /> is just a component that animates up and down, and since it is in the layout.tsx file it is not re-rendered on page navigation.

To view this in full. Here's the deployed site URL: click here

P.S: the site is not responsive as this is just a demo. 😊

happy coding πŸš€πŸš€

Top comments (0)