fix: prevent theme flicker on page load

Add blocking script in HTML head to apply theme before React hydration.
This eliminates the flash of wrong theme (FOUT) that occurred when the
page loaded with default theme before useEffect could apply the saved theme.

The script:
- Runs synchronously before page render
- Reads theme from localStorage
- Applies dark/light class to <html> element immediately
- Handles system theme preference detection
- Wrapped in try-catch for safety

This ensures users see the correct theme from the first paint, with no flicker.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-08 17:18:28 +01:00
parent f1fc803b0e
commit 1e1489ec58

View File

@@ -14,6 +14,30 @@ export default function RootLayout({
}>) { }>) {
return ( return (
<html lang="en" suppressHydrationWarning> <html lang="en" suppressHydrationWarning>
<head>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
const storageKey = 'units-ui-theme';
const stored = localStorage.getItem(storageKey);
const theme = stored || 'system';
if (theme === 'system') {
const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
document.documentElement.classList.add(systemTheme);
} else {
document.documentElement.classList.add(theme);
}
} catch (e) {}
})();
`,
}}
/>
</head>
<body className="antialiased"> <body className="antialiased">
<ThemeProvider defaultTheme="system" storageKey="units-ui-theme"> <ThemeProvider defaultTheme="system" storageKey="units-ui-theme">
{children} {children}