Where to put providers in NextJs 13?
Asked Answered
C

1

3

I'm using the date library by Mui and it requires a provider to be wrapped around all components:

import { LocalizationProvider } from '@mui/x-date-pickers';
import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'

function App({ children }) {
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      {children}
    </LocalizationProvider>
  );
}

But there's no corresponding App function in NextJs 13 which only offers pages in the /app directory.

Chiefly answered 10/7, 2023 at 12:17 Comment(1)
use the RootLayout fileCromorne
M
8

The problem is that the provider does not declare "use client" and calls createContext which is not allowed on server side components like Next.JS layouts.

One pattern to create compatibility (inspired by TanStack Query's Advanced Server Rendering guide) is to create a <Providers/> client component which accepts & renders children. Wrap your MUI provider around the {children} in that component.

'use client' // <-- Important!

export default function Providers({ children }) {
  // Add other providers nested here as needed
  return (
    <LocalizationProvider dateAdapter={AdapterDayjs}>
      {children}
    </LocalizationProvider>
  )
}

Then import <Providers/> into layout.tsx as a child of <body>

// In Next.js, this file would be called: app/layout.jsx
import Providers from './providers'

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <head />
      <body>
        <Providers>{children}</Providers>
      </body>
    </html>
  )
}

This essentially just re-exports the Provider as a client component so that Next.JS does not try to treat it as a server component.

Matless answered 7/2 at 11:30 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.