From b9ee6f9ae0f017868ff5c180b0e7f1c3c4d7b743 Mon Sep 17 00:00:00 2001 From: theoribbi Date: Mon, 21 Jul 2025 11:02:25 +0200 Subject: [PATCH] fix(theme): resolve hydration mismatch in code block component Add mounted state check to prevent theme mismatch during hydration Use resolvedTheme instead of applicationTheme for consistent theming Remove hardcoded background color in favor of CSS variables --- app/(site)/layout.tsx | 5 ++++- components/ui/code-block.tsx | 40 ++++++++++++++++++++++++++++++++---- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/app/(site)/layout.tsx b/app/(site)/layout.tsx index f49e62d..e31467a 100644 --- a/app/(site)/layout.tsx +++ b/app/(site)/layout.tsx @@ -13,9 +13,12 @@ export default function SiteLayout({ }: Readonly<{ children: React.ReactNode; }>) { - const { resolvedTheme } = useTheme(); // Suppression de theme non utilisé + const { resolvedTheme, theme } = useTheme(); // Suppression de theme non utilisé const [mounted, setMounted] = React.useState(false); + console.log(theme); + + React.useEffect(() => { setMounted(true); }, []); diff --git a/components/ui/code-block.tsx b/components/ui/code-block.tsx index 5f5b5bb..adedf89 100644 --- a/components/ui/code-block.tsx +++ b/components/ui/code-block.tsx @@ -46,10 +46,16 @@ export function CodeBlock({ maxVisibleLines = 10, defaultExpanded = false, }: CodeBlockProps) { - const { theme: applicationTheme } = useTheme(); + const { theme: applicationTheme, resolvedTheme } = useTheme(); const [copied, setCopied] = React.useState(false); const [localActiveTab, setLocalActiveTab] = React.useState(activeTab || (tabs && tabs.length > 0 ? tabs[0].value : undefined)); const [isExpanded, setIsExpanded] = React.useState(defaultExpanded); + const [mounted, setMounted] = React.useState(false); + + // Fix hydration issues with next-themes + React.useEffect(() => { + setMounted(true); + }, []); const handleCopy = () => { const textToCopy = tabs && localActiveTab @@ -110,7 +116,7 @@ export function CodeBlock({ case 'shell': return ( - + ); case 'css': @@ -212,7 +218,32 @@ export function CodeBlock({ ] }; - const theme = applicationTheme === "dark" ? customDarkTheme : themes.github; + const theme = resolvedTheme === "dark" ? customDarkTheme : themes.github; + + // Don't render until mounted to avoid hydration mismatch + if (!mounted) { + return ( +
+ {showHeader && ( +
+
+ {headerPrefix} + {getLanguageIcon(activeLanguage)} + {title &&
{title}
} +
+
+ +
+
+ )} +
+
+            {displayedCode.trim()}
+          
+
+
+ ); + } return (
@@ -310,7 +341,8 @@ export function CodeBlock({ )} style={{ ...style, - backgroundColor: applicationTheme === "dark" ? "#1a1a1a" : style.backgroundColor, + // Remove hardcoded background, let CSS variables handle it + backgroundColor: undefined, }} > {tokens.map((line, i) => {