Home > Mobile >  Is It Best Practice To Use MUI 5 ThemeProvider Only in "_app.js" or Is It Ok To Use On Eve
Is It Best Practice To Use MUI 5 ThemeProvider Only in "_app.js" or Is It Ok To Use On Eve

Time:12-03

MUI 5 newbie question concerning ThemeProvider. Looking at the documentation at https://mui.com/customization/theming/ I see several examples, such as the one provided below, where a custom themed material component is wrapped with ThemeProvider in order to apply custom styles.

export default function CustomStyles() {
  return (
    <ThemeProvider theme={theme}>
      <CustomCheckbox defaultChecked />
    </ThemeProvider>
  );
}

I've also seen examples where ThemeProvider is used in "_app.js" to apply custom theme styles globally, as shown below.

export default function MyApp(props) {
  const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;

  return (
    <CacheProvider value={emotionCache}>
      <Head>
        <title>My page</title>
        <meta name="viewport" content="initial-scale=1, width=device-width" />
      </Head>
      <ThemeProvider theme={theme}>
        <Header />
        {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
        <CssBaseline />
        <Component {...pageProps} />
      </ThemeProvider>
    </CacheProvider>
  );
}

I'm really confused as to which of the two is best practice, maybe the answer is both. Is it safe to say that I would generally want to put all of my global theme styles in my ThemeProvider wrapper that is applied to "_app.js" but for any one-offs or custom styling applicable to a specific component it is then safe to wrap the specific component with yet another ThemeProvider wrapper to apply the custom styling specific to that component? I just feel like I'm using ThemeProvider over and over again for custom components and it doesn't feel right.

CodePudding user response:

I suggest you to use ThemeProvider in the top level of a React app once even though it could be multiple and nested.

Let's say your app has a setting which can select your custom theme like 'light' or 'dark'.

In this case, you need to toggle a selected theme, which can be from React Context API.

// src/App.js
...
import { createTheme, ThemeProvider } from '@mui/material';
const theme = createTheme(themeOption);

return (
  <ThemeProvider theme={theme}>
    <Router>
      <Route>...
    </Router>
  </ThemeProvider>
);
...

Please have a look if you want to know more. Material ui use palette primary color based on selected theme mode

  • Related