reactjstypescriptnext.jsmaterial-ui

NextJs hydration error when using MUI library


So I have server side rendering with page.tsx like so:

import Button from '@mui/material/Button'

export default async function Home() {
  return (
    <div>
       <Button variant="contained" >Home</Button>
    </div>
  );
}

But it's mad at a hydration message:

'Uncaught Error: Hydration failed because the server rendered HTML didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:'

I can fix this by making it with a 'use client' at the top. But what if I want to keep it a server side page.tsx? I tried 2 and 3 but they didn't work here: https://nextjs.org/docs/messages/react-hydration-error


Solution

  • I have no idea what versions you're using, your next version, your mui version.
    but make sure to use the AppRouterCacheProvider in the root of your project like so:

    +import { AppRouterCacheProvider } from '@mui/material-nextjs/v15-appRouter';
     // or `v1X-appRouter` if you are using Next.js v1X
    
     export default function RootLayout(props) {
       return (
         <html lang="en">
           <body>
    +        <AppRouterCacheProvider>
               {props.children}
    +        </AppRouterCacheProvider>
           </body>
         </html>
       );
     }
    

    you can get more info about it here: MUI Next.js integration