I created a brand new Next.js application that uses the app
folder. Then I installed Materiel UI and started using the examples given in the documentation. But I get this error:
Type error: createContext only applies to client components. Add a "use client" directive at the top of the file to use it.
Here is an example of documentation in my code:
import Button from "@mui/material/Button"; export default function Home() { return ( <div> <Button variant="contained">Hello World</Button> </div> ); }
I want this button to appear on my page. I know adding "use client"
at the top will fix the error, but I want my page to render on the server.
To make MUI work perfectly with SSR, you need to make some adjustments: https://github.com/mui/material-ui/tree/master/examples/material-next-app-router-ts.
Note: Even if you configure it correctly, the button can be rendered server-side, but you cannot assign the onClick handler (if I remember correctly)
Apparently the button you are importing is using a client hook, in this case
createContext
. To do this, you need to add"use client"
at the top of the file. But this means that the page becomes a client component and does not cease to be a server component.If this bothers you, you can create a
lib
folder at the same level asapp
and add themui.js file in it as follows Show:
Then you import it from there (this way, the rest of the page is still a server component):
Side note, you may encounter a similar error when setting up the context. This means you are trying to set it in the server component. The guideline is to add this to its own "Use Client" tag file:
and import it from there:
For a more detailed answer, check out this thread.