MUI createTheme is not properly passing theme to MUI components

Solution 1:

Change this line:

import { ThemeProvider } from "@mui/styles";

To:

import { ThemeProvider } from "@mui/material/styles";

Reason: There are 2 ThemeProviders here

  • The one from @mui/styles: This ThemeProvider does send the Theme object down via context, it works fine, you can still access it using the useTheme hook:
const theme = useTheme();

return <Box sx={{ width: 10, height: 10, bgcolor: theme.palette.primary.main }} />
  • The one from @mui/material/styles: This ThemeProvider is a wrapper of the above, but it also injects the theme to the StyledEngineThemeContext.Provider, which allows you to access the theme when using MUI API (sx prop/styled()). The problem here is that the Button and Menu components uses the styled() API under-the-hood so the ThemeProvider needs to be imported from @mui/material/styles to make it work.
return <Box sx={{ width: 10, height: 10, bgcolor: 'primary.main' }} />

Related answers

  • Difference between @mui/material/styles and @mui/styles?
  • Cannot use palette colors from MUI theme
  • MUI - makeStyles - Cannot read properties of undefined
  • Material UI Dark Mode