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.
RootLayout
file – Cromorne