Currently using Next.js 14 and MUI v5.
I am using CssVarsProvider to prevent flicker on color mode changes. Texts and background colors are changing well on refresh. But my darkmodebutton (showing lightmodeicon/darkmodeicon) is always in default mode on refresh. It seems there is a hydration issue. How should I get the current theme mode on refresh, and provide a correct image without flickering?
ThemeRegistry.js
<CssVarsProvider theme={theme} defaultMode="dark">
<CssBaseline />
{children}
</CssVarsProvider>
root layout.js
<body style={{ display: "flex", flexDirection: "column" }}>
{getInitColorSchemeScript({
attribute: "data-mui-color-scheme",
modeStorageKey: "mui-mode",
colorSchemeStorageKey: "mui-color-scheme",
defaultMode: "dark",
})}
<LinearLoadingBar />
<ThemeRegistry>
<Header />
{children}
<Footer />
</ThemeRegistry>
</body>
DarkModeButton inside layout.js <Header/>
export function DarkModeButton() {
const { mode, setMode } = useColorScheme();
return (
<Button
variant="outlined"
disableRipple
onClick={() => {
setMode(mode === "light" ? "dark" : "light");
}}
sx={{ minWidth: 0, p: 1, height: "36px" }}
style={{ color: theme.vars.palette.text.main }}
>
{mode === "light" ? (
<LightModeIcon fontSize="small" />
) : (
<DarkModeIcon fontSize="small" />
)}
</Button>
);
}