Next.js Discord

Discord Forum

Layouts and AppRouter

Unanswered
Persian posted this in #help-forum
Open in Discord
PersianOP
I'm getting back into NextJS development and trying to catch up with the new features available with App Router. I love the new layout files available for every page but I'm a bit confused about how to organize the main layout. Putting the whole thing into the app/layout.tsx along with all the technical stuff like the Contexts and MUI initiation and others seems kinda' convoluted and I'd really prefer to encapsulate the layout itself separately.

Is it considered a good practice to have something like this there?
    <html lang="en">
      <body>
        <AppRouterCacheProvider>
          <ThemeProvider theme={theme}>
            <CssBaseline />
            <MainLayout>{children}</MainLayout>
          </ThemeProvider>
        </AppRouterCacheProvider>
      </body>
    </html>

4 Replies

Plott Hound
Hi there. this is a very common pattern:
https://vercel.com/guides/react-context-state-management-nextjs#rendering-third-party-context-providers-in-server-components

the idea is that you have a special providers file (often marked with use client) that you can add all of your context providers to then import and wrap that component in your layout file
It's also fine to make another wrapper component for all of your layout related things and use that in layout instead of having all the code there itself. the same way you did it in your example
this has the added benefit that you can even mark these layout wrappers as use client (if needed) while still allowing all of its children to be server rendered
one thing to be aware of is that each layout you create will inherit and be wrapped by its parent layout so i'd generally recommend to keep the root layout as simple as possible so you avoid situations where you have a child layout but dont want it to have included things from the parent layouts