fix: resolve ThemeToggle hydration error and incorrect icon (#648)

- Added mounted state to prevent SSR/client hydration mismatch
- Show Sun icon in dark mode, Moon icon in light mode
- Render placeholder during SSR to maintain layout stability
- Fixed className prop not being applied

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
Abelino Chavez 2026-01-29 14:08:55 -06:00
parent 4d77e3f2bb
commit 55a29bea9f
1 changed files with 20 additions and 0 deletions

View File

@ -1,5 +1,6 @@
"use client";
import { useEffect, useState } from "react";
import { Button } from "./ui/button";
import { useTheme } from "next-themes";
import { cn } from "@/utils/ui";
@ -18,6 +19,25 @@ export function ThemeToggle({
onToggle,
}: ThemeToggleProps) {
const { theme, setTheme } = useTheme();
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
// Prevent hydration mismatch by not rendering theme-dependent content until mounted
if (!mounted) {
return (
<Button
size="icon"
variant="ghost"
className={cn("size-8", className)}
>
<span className={cn("!size-[1.1rem]", iconClassName)} />
<span className="sr-only">Toggle theme</span>
</Button>
);
}
return (
<Button