fix(theme): guard theme-icon rendering against SSR/client hydration mismatch
resolvedTheme from next-themes is undefined during SSR and on the client's first paint (before its mount effect runs), so ThemeToggleButton and the shared useThemeToggle hook (Sidebar, MobileNav) rendered a Sun/Moon icon that could mismatch the server-rendered one on first hydration whenever the system/stored theme was dark -- a React #418 hydration error. Both now gate isDark on a mounted flag, matching next-themes' documented hydration-safe pattern. Found via a Chrome DevTools Lighthouse re-check on the SpeedUp-Plan work (Gitea #28) -- pre-existing, unrelated to the Clerk-provider scoping.
This commit is contained in:
1 parent
383817916d
commit
556aac7e22
2 files changed
+17
-2
No files matched your search
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { Moon, Sun } from "lucide-react";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useTranslations } from "next-intl";
|
||||
@@ -11,7 +12,15 @@ import { useTranslations } from "next-intl";
|
||||
export function ThemeToggleButton() {
|
||||
const { resolvedTheme, setTheme } = useTheme();
|
||||
const t = useTranslations("Theme");
|
||||
const isDark = resolvedTheme === "dark";
|
||||
|
||||
// resolvedTheme is undefined on the server and on the client's first paint
|
||||
// (next-themes only knows the real value after its own mount effect runs).
|
||||
// Gating on `mounted` keeps the icon at the server-rendered default (Moon)
|
||||
// until hydration is done, avoiding a React #418 hydration mismatch when
|
||||
// the system/stored theme is dark.
|
||||
const [mounted, setMounted] = useState(false);
|
||||
useEffect(() => setMounted(true), []);
|
||||
const isDark = mounted && resolvedTheme === "dark";
|
||||
|
||||
return (
|
||||
<button
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTheme } from "next-themes";
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { useTRPC } from "@/trpc/client";
|
||||
@@ -15,7 +16,12 @@ export function useThemeToggle() {
|
||||
const trpc = useTRPC();
|
||||
const mutation = useMutation(trpc.owner.setThemePreference.mutationOptions());
|
||||
|
||||
const isDark = resolvedTheme === "dark";
|
||||
// Same next-themes hydration guard as ThemeToggleButton (SpeedUp-Plan,
|
||||
// React #418): resolvedTheme is undefined until after mount, so consuming
|
||||
// it directly on first client render can mismatch the server-rendered icon.
|
||||
const [mounted, setMounted] = useState(false);
|
||||
useEffect(() => setMounted(true), []);
|
||||
const isDark = mounted && resolvedTheme === "dark";
|
||||
|
||||
const setDark = (dark: boolean) => {
|
||||
setTheme(dark ? "dark" : "light");
|
||||
|
||||
Reference in new issue
Block a user