Skip to content
Tutorials Center
My learning

Topics

Lesson 20 of 36 ยท Theming and Customization

Dark Mode and Color Schemes

Add dark mode to Material UI with colorSchemes, CSS variables, useColorScheme and a system-preference toggle, without a flash of the wrong theme.

Users expect an app to follow their operating system's light or dark setting, and many want a switch to override it. Material UI supports this in two ways. The older way builds two separate themes and swaps them in React state. The modern way, available since v6, builds one theme with several color schemes that are exposed as CSS variables. The browser changes the colors without React re-rendering the tree, and there is no flash of the wrong colors when the page loads.

This lesson shows both, then explains why the second is the better default.

MUI is not available inside the live editors here. Real MUI code is read-only; the runnable examples are stand-ins that copy the same technique (CSS variables plus an attribute on the root element).

The simple way: palette.mode

The palette.mode option switches all default palette values between light and dark. You can build the theme from state:

JSX
// Real Material UI, read-only
import { useMemo, useState } from 'react';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import useMediaQuery from '@mui/material/useMediaQuery';

export function App() {
  const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');
  const [mode, setMode] = useState(prefersDark ? 'dark' : 'light');
  const theme = useMemo(() => createTheme({ palette: { mode } }), [mode]);
  return (
    <ThemeProvider theme={theme}>
      {/* ... */}
    </ThemeProvider>
  );
}

This works, but it has two drawbacks. On the server useMediaQuery cannot know the user's preference, so server-rendered HTML is usually light and then flips to dark after hydration (a visible flash). And switching the theme re-renders every component that reads it.

The modern way: colorSchemes and CSS variables

With cssVariables: true, MUI writes every theme value as a CSS custom property (--mui-palette-primary-main). With colorSchemes, it writes one set of variables per scheme and selects the right one with a CSS selector (by default [data-mui-color-scheme="dark"], or a media query for the system setting).

JSX
// Real Material UI, read-only
import { createTheme, ThemeProvider } from '@mui/material/styles';

const theme = createTheme({
  cssVariables: true,
  colorSchemes: {
    light: {
      palette: { primary: { main: '#0b6e4f' } },
    },
    dark: {
      palette: { primary: { main: '#5fd3a8' }, background: { default: '#10151a' } },
    },
  },
});

If you only write colorSchemes: { dark: true }, MUI generates a standard dark palette. By default the app follows the system setting; you can also pick a scheme by hand.

Toggling with useColorScheme

useColorScheme returns the current mode ('light', 'dark' or 'system'), the resolved systemMode, and setMode:

JSX
// Real Material UI, read-only
import { useColorScheme } from '@mui/material/styles';
import Button from '@mui/material/Button';

function ModeSwitch() {
  const { mode, setMode } = useColorScheme();
  if (!mode) {
    return null; // not known on the server or on the first render
  }
  return (
    <Button onClick={() => setMode(mode === 'dark' ? 'light' : 'dark')}>
      {mode} mode
    </Button>
  );
}

Two details matter. First, mode is undefined until the client has read the saved choice, so render null (or a placeholder of the same size) to avoid a hydration mismatch. Second, the chosen mode is saved in localStorage under mui-mode, so it survives reloads and is shared between tabs.

Styling per scheme

When a style must differ between schemes, use the theme's applyStyles helper. It returns a CSS selector that matches only that scheme:

JSX
// Real Material UI, read-only
<Box
  sx={(theme) => ({
    border: '1px solid #ccc',
    ...theme.applyStyles('dark', { borderColor: '#444' }),
  })}
/>

In your own styled components, write colors with theme.vars.palette... (which yields var(--mui-palette-...)) rather than theme.palette... (a fixed color string), so they follow the active scheme without re-rendering.

theme.palette.primary.main is a concrete color for one scheme. theme.vars.palette.primary.main is the CSS variable that points at the active scheme. With cssVariables enabled, use vars for anything that should react to dark mode.

Why variables are better

flowchart LR
  A["Click: setMode('dark')"] --> B["data attribute on html changes"]
  B --> C["CSS variables switch values"]
  C --> D["Browser repaints; React tree untouched"]

With CSS variables the browser does the work, so a mode switch does not re-render the component tree.

Try it: a scheme switch built on CSS variables

This stand-in uses the same mechanism. A theme object per scheme is turned into CSS variables on a wrapper; the toggle changes a data-scheme attribute. The mode has three values: light, dark and system. Components only use var(--palette-...), so they never re-render when the scheme changes.

Light, dark and system with CSS variables

Avoiding the flash on first load

When the page is rendered on the server, the HTML does not know the user's saved mode. The browser paints the default scheme, then your script runs and the colors flip. To avoid it, put a tiny blocking script in the document <head> that reads the saved mode and sets the attribute before the first paint. MUI ships it as InitColorSchemeScript:

JSX
// Real Material UI, read-only (for example in a layout file)
import InitColorSchemeScript from '@mui/material/InitColorSchemeScript';

<html lang="en" suppressHydrationWarning>
  <body>
    <InitColorSchemeScript attribute="data-mui-color-scheme" />
    {children}
  </body>
</html>

The Next.js lessons (Next.js App Router Setup and SSR, Emotion and the Theme Flash) show it in a full layout.

Try it: the flash, reproduced

The next demo mimics a saved preference being applied before or after the first paint. Press the buttons to replay each load. In the "late" version you can see the wrong scheme flicker.

Applying the saved mode early or late

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the colorSchemes approach avoid re-rendering the tree on a mode switch?

    Each scheme is a set of CSS variables selected by an attribute or media query. Switching changes the selector, not React state that every component reads.
  2. 2. Why should ModeSwitch return null while mode is undefined?

    useColorScheme reads the stored choice on the client. Before that the value is undefined, so render nothing or a same-size placeholder.
  3. 3. Which value should you use in a styled component so it follows dark mode without re-rendering?

    theme.vars.* returns the CSS variable reference, which changes with the scheme. theme.palette.* is a single concrete color.
  4. 4. What does InitColorSchemeScript do?

    It sets the color scheme attribute early from localStorage or the system preference so the first paint already has the right colors.

Summary

  • palette.mode swaps one palette between light and dark but needs state and re-renders, and it can flash on the server.
  • cssVariables: true plus colorSchemes gives one theme with several schemes as CSS variables.
  • useColorScheme exposes mode, systemMode and setMode; handle the undefined first render.
  • Use theme.vars and theme.applyStyles('dark', ...) for scheme-specific styling.
  • InitColorSchemeScript removes the flash for server-rendered apps.

Next: The sx Prop and styled()