From 556aac7e227a4aba20c656f63420bb67d6c561e3 Mon Sep 17 00:00:00 2001 From: neodk2004 Date: Thu, 20 Aug 2026 20:11:55 +0200 Subject: [PATCH] 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. --- src/components/landing/ThemeToggleButton.tsx | 11 ++++++++++- src/hooks/useThemeToggle.ts | 8 +++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/components/landing/ThemeToggleButton.tsx b/src/components/landing/ThemeToggleButton.tsx index 57f2115..d1d8934 100644 --- a/src/components/landing/ThemeToggleButton.tsx +++ b/src/components/landing/ThemeToggleButton.tsx @@ -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 (