Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 72 ยท Optimization and SEO

Using Material UI and Other Component Libraries

Use Material UI in the Next.js App Router with the Emotion cache registry, theme provider and client boundaries, and compare shadcn/ui, Radix, Chakra and others.

A component library gives you buttons, inputs, tables, dialogs and a consistent look so that you do not draw each from scratch. Material UI (MUI), Chakra UI, shadcn/ui and Radix are popular choices. In a plain React single-page app you install the package, wrap your app in a provider and start importing components. In the App Router there is a twist: Server Components cannot use state, context or effects, and many styling libraries are built on exactly those things.

This lesson explains the two questions you must answer for any library: does it need a Client Component boundary? and how do its styles get into the server-rendered HTML? It then works through Material UI in detail, and compares shadcn/ui, Radix, Chakra and Tailwind-based kits. Next.js and these libraries cannot run on this site, so the real code is read-only, and the runnable examples are Node.js stand-ins that model the two ideas that matter most: collecting styles while rendering, and merging a theme.

Library APIs change faster than Next.js itself. The shapes below are stable, but import paths and package names (especially the versioned ones) move between releases. Always read the library's current Next.js guide before copying configuration.

Two questions for every library

Client boundary? Does it use state, context or effects?
How do styles arrive? Runtime CSS-in-JS needs a registry. CSS files do not.

Answers decide the setup.

1 / 2

The client boundary

Many library components use hooks or context inside, so they are Client Components. That is fine: a Server Component may import and render a Client Component. What you cannot do is pass things across the boundary that cannot be serialized, such as functions. Two common mistakes:

  • Passing an onClick function from a Server Component to a library button. Wrap the button in your own small "use client" file that owns the handler.
  • Using a library's context provider in app/layout.tsx (a Server Component). The provider uses createContext, so it must live in a Client Component. Create a small Providers file with "use client", and render inside it. This works because children passed as props can still be Server Components (see Server and Client Composition).
TSX
// app/providers.tsx (read-only)
"use client";

import type { ReactNode } from "react";
import { SomeLibraryProvider } from "some-library";

export function Providers({ children }: { children: ReactNode }) {
  return <SomeLibraryProvider>{children}</SomeLibraryProvider>;
}

Newer versions of most libraries already mark their components with "use client" inside the package, so you can import them directly in a Server Component as long as you pass only simple props. If an import fails with an error about hooks or context in a Server Component, wrapping it in your own client file is the fix.

How styles reach the page

Libraries differ in how they produce CSS:

Approach Examples Effect in the App Router
Plain CSS files or utility classes shadcn/ui with Tailwind, Mantine (CSS), CSS Modules No extra work. Styles are in the bundle like any other CSS.
Runtime CSS-in-JS Material UI (Emotion), Chakra UI (Emotion), styled-components Styles are created while components render. A registry must collect them during server rendering and insert them into the HTML, or the page flashes unstyled.
Build-time CSS Panda CSS, vanilla-extract, StyleX CSS is extracted at build. No registry.

The idea of the registry is simple: the server renders a component, the library records each style rule it needed, and the registry then writes those rules into a <style> tag with the useServerInsertedHTML hook (see CSS and Styling). The stand-in below models that process with a tiny style engine. Notice that the same style used twice becomes one class and one rule, and that the output is a complete <style> block that can go in the HTML before the markup.

Node.js A style registry: collect rules while rendering

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If the registry is missing, the HTML arrives without styles, the browser shows plain markup for a moment and then the library injects its styles on the client. You see a flash of unstyled content (FOUC), and sometimes a hydration warning.

Material UI step by step

Material UI implements Google's Material Design. Its components are styled with Emotion. Install MUI, Emotion and the Next.js integration package:

Terminal
npm install @mui/material @emotion/react @emotion/styled @mui/material-nextjs

Step 1: the cache provider. The @mui/material-nextjs package contains AppRouterCacheProvider, which is the registry for the App Router. It lives in the root layout. Its import path contains the Next.js version it supports (for example v15-appRouter or v16-appRouter), so use the one named in the MUI documentation for your version.

TSX
// app/layout.tsx (read-only)
import { AppRouterCacheProvider } from "@mui/material-nextjs/v15-appRouter";
import { Roboto } from "next/font/google";
import { Providers } from "./providers";

const roboto = Roboto({ weight: ["300", "400", "500", "700"], subsets: ["latin"], display: "swap" });

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en" className={roboto.className}>
      <body>
        <AppRouterCacheProvider options={{ enableCssLayer: true }}>
          <Providers>{children}</Providers>
        </AppRouterCacheProvider>
      </body>
    </html>
  );
}

The font comes from next/font (see Fonts and Scripts), so Roboto is served from your own domain and does not block rendering. The option enableCssLayer puts MUI's CSS in a CSS cascade layer, which makes it easy to override with Tailwind or your own CSS.

Step 2: the theme provider in a client file. A theme is a plain object, but ThemeProvider uses context, so it needs "use client".

TSX
// app/providers.tsx (read-only)
"use client";

import type { ReactNode } from "react";
import { ThemeProvider, createTheme, CssBaseline } from "@mui/material";

const theme = createTheme({
  cssVariables: true,
  palette: { primary: { main: "#1976d2" } },
  typography: { fontFamily: "inherit" },
});

export function Providers({ children }: { children: ReactNode }) {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      {children}
    </ThemeProvider>
  );
}

CssBaseline resets browser defaults the Material way. Setting cssVariables: true makes the theme available as CSS variables, which helps with server rendering and dark mode.

Step 3: use components. A page that only lays out MUI components, without handlers, can stay a Server Component:

TSX
// app/page.tsx (read-only)
import Button from "@mui/material/Button";
import Typography from "@mui/material/Typography";
import Stack from "@mui/material/Stack";
import Link from "next/link";

export default function Home() {
  return (
    <Stack spacing={2} sx={{ p: 4 }}>
      <Typography variant="h4" component="h1">Welcome</Typography>
      <Button component={Link} href="/dashboard" variant="contained">
        Open dashboard
      </Button>
    </Stack>
  );
}

component={Link} makes the MUI button render a next/link, so navigation stays client-side. Two details trip people up. First, import from the deep path (@mui/material/Button) rather than the barrel (@mui/material) in large projects, or configure optimizePackageImports in next.config.ts (see Bundle Size and Performance); Next.js already does this automatically for @mui/material. Second, the sx prop accepts functions in some cases (sx={{ color: (theme) => theme.palette.primary.main }}), and a function cannot be passed from a Server Component. Use a client component for those.

The theme itself is a deep merge of your overrides onto defaults. The stand-in below does a small version of createTheme, including theme.spacing(), so you can see why sx={{ p: 4 }} means 32 pixels.

Node.js createTheme as a deep merge, and the spacing function

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Step 4: Server Component restrictions. Because MUI relies on context for the theme, a component such as Button needs ThemeProvider above it. Since the provider is already in the layout, this works for the whole tree. But anything you build with styled() from @mui/material/styles and place in a Server Component can hit the Client Component rules, so keep styled and hook-based code (useTheme, useMediaQuery) in client files.

shadcn/ui and Radix

Radix UI (the "Primitives") provides accessible, unstyled building blocks: dialog, dropdown menu, tabs, popover and so on. They handle focus, keyboard and ARIA attributes, and you style them yourself. Their components are Client Components.

shadcn/ui is different from the others: it is not a package you import. A command-line tool copies component source files into your project, usually components/ui/button.tsx, written with Radix primitives, Tailwind CSS and a small helper for class names. You own the code and can edit it.

Terminal
npx shadcn@latest init
npx shadcn@latest add button dialog
TSX
// app/page.tsx (read-only)
import { Button } from "@/components/ui/button";

export default function Home() {
  return <Button variant="outline">Click me</Button>;
}

Why many teams choose it for the App Router: styles are Tailwind classes (plain CSS, no registry, no runtime cost), there is no provider to wire up for simple components, and you can change anything because the source is yours. The trade-off is that you also maintain that code and merge upstream improvements yourself. See CSS and Styling for Tailwind in Next.js.

Chakra UI, Mantine and others

  • Chakra UI uses Emotion in its older versions and a provider component. Create a "use client" provider file and wrap the layout, as in the generic example above. Follow its Next.js guide for the registry details of your version.
  • Mantine ships CSS files and a MantineProvider, plus a script that sets the color scheme before paint. Import its stylesheet in the root layout, add the provider in a client file, and add the ColorSchemeScript to the <head>.
  • Ant Design, NextUI/HeroUI and PrimeReact each publish an App Router guide. Ant Design has a registry package like MUI's.
  • Headless libraries (Headless UI, React Aria) behave like Radix: client components, no styles, no registry.

Choosing a library

  1. Prefer libraries that ship plain CSS or use Tailwind if you can, because they have the fewest App Router surprises and no runtime style cost.
  2. If you pick a runtime CSS-in-JS library such as MUI, budget for the registry setup and the extra client JavaScript, and measure your bundle (Bundle Size and Performance).
  3. Check that the library documents the App Router, not only the Pages Router. If its docs mention _document.tsx for styles, the guide is outdated.
  4. Wrap third-party components in your own components (components/ui/), so that replacing a library later touches one folder.
  5. Always test the page with JavaScript disabled: the content and styles should still appear, since that is what server rendering is for.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does a runtime CSS-in-JS library such as Material UI need a registry in the App Router?

    The styles are produced while components render. The registry records them and writes them into the HTML stream so the first paint is already styled.
  2. 2. Where should a ThemeProvider that uses context be placed?

    Context only exists in Client Components. A client Providers file can still render Server Component children.
  3. 3. What makes shadcn/ui different from a package like Material UI?

    A CLI copies the component files into your repo. Because styles are Tailwind classes there is no runtime style engine.
  4. 4. A Server Component passes onClick={() => save()} to a library Button and the build fails. What is the fix?

    Functions cannot cross from a Server Component to a Client Component as props. Put the handler in a file with 'use client'.

Summary

  • For every library ask two questions: does it need a Client Component boundary, and how do its styles reach the server-rendered HTML?
  • Context providers go in a small "use client" file rendered from the layout; children can still be Server Components.
  • Runtime CSS-in-JS (MUI, Chakra, styled-components) needs a registry that collects styles during rendering. Plain CSS and Tailwind-based kits do not.
  • MUI setup: AppRouterCacheProvider in the root layout, ThemeProvider and CssBaseline in a client file, next/font for Roboto, component={Link} for navigation.
  • Radix gives unstyled accessible primitives; shadcn/ui copies Tailwind-styled components built on Radix into your repo.
  • Prefer CSS-based libraries where you can, wrap third-party components in your own, and measure the bundle.

Next: Bundle Size and Performance