最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

next.js - MUI v5 CssVarsProvider hydration issue on color mode - Stack Overflow

programmeradmin4浏览0评论

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>
  );
}
发布评论

评论列表(0)

  1. 暂无评论