Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
How to nest Context and MUI's theme provider?

So I currently have a state to toggle dark / light mode on a website with lots of nested components. I have a root App.js:

function App() {
    return (
        <DarkModeProvider>
            <div className="App">
                <HomePage />
            </div>
        </DarkModeProvider>
    );
}

The DarkModeProvider is my react context, and in the next component I have a layout where I have my navigation and routing, that is wrapped in the ThemeProvider:

const HomePage = () => {
const { isDarkTheme } = useContext(DarkModeContext);

return (
    <ThemeProvider theme={isDarkTheme ? createTheme(darkTheme) : 

createTheme(lightTheme)}>
            <DrawerProvider>
                <Router>
                    <Box sx={{ display: "flex" }}>
                        <Box>
                            <HomePageInner />
                        </Box>

                        <Routes>
                            <Route path="/inventory" element={<Inventory />} />
                            <Route path="/orders" element={<Orders />} />
                            <Route path="/vendors" element={<Vendors />} />
                        </Routes>
                    </Box>
                </Router>
            </DrawerProvider>
        </ThemeProvider>
    );
};

It works fine, however, I'd like to access the theme context in my "app" class that's in the root App component. If I wrap the DarkModeProvider with the ThemeProvider, I don't have access to the state of the dark / light mode, if I wrap the ThemeProvider with the DarkModeProvider, I lose access to the isDarkTheme state from my context.

Is there a better practice to format this? What I really want is to have a css / style sheet in the source folder as the same level as the app component. I'm unsure how to access my theme provider when it's not in my app component. OR how to have my dark mode state accessible while wrapped inside of the theme provider (or vice versa).

For example my App.CSS:

body {
    background-color: theme.primary.palette.main; 
    /* I would like the body to follow my MUI theme. */
}

a {
    color: inherit;
    text-decoration: none;
}

Dark Mode Provider:

import { createContext, useState } from "react";

const DarkModeContext = createContext();

export const DarkModeProvider = ({ children }) => {
    const [isDarkTheme, setIsDarkTheme] = useState(false);

    const changeTheme = () => {
        setIsDarkTheme(!isDarkTheme);
    };

    return (
        <DarkModeContext.Provider
            value={{
                isDarkTheme,
                changeTheme,
            }}
        >
            {children}
        </DarkModeContext.Provider>
    );
};

export default DarkModeContext;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can move the ThemeProvider component inside App.js file and have a state there for isDarkTheme which you can then use both for DarkModeProvider and ThemeProvider

function App() {
  const [isDarkTheme, setIsDarkTheme] = useState(false);

  const changeTheme = () => {
    setIsDarkTheme(!isDarkTheme);
  };
  
  return (
      <DarkModeProvider value={{ isDarkTheme, changeTheme }}>
        <ThemeProvider theme={isDarkTheme ? createTheme(darkTheme) : createTheme(lightTheme)}>
          <div className="App">
            <HomePage />
          </div>
        </ThemeProvider> 
      </DarkModeProvider>
  );
}

Dark Mode Provider:

import { createContext } from "react";

const DarkModeContext = createContext();

export const DarkModeProvider = ({ children, value }) => {
    return (
        <DarkModeContext.Provider value={value}>
          {children}
        </DarkModeContext.Provider>
    );
};

export default DarkModeContext;
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda