fix: prevent flash of light theme on marketplace load

Add inline script to root layout that reads the stored theme preference
from cookie/localStorage synchronously before React hydrates, eliminating
the light→dark flash for users who prefer dark mode.

Also guard the theme storage write with the hydrated flag so the initial
render does not overwrite a stored 'dark' preference with 'light'.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
root
2026-05-23 02:54:10 -04:00
parent 4268e5c379
commit b82a5d4633
2 changed files with 13 additions and 2 deletions
+8
View File
@@ -17,6 +17,14 @@ export default function RootLayout({ children }: { children: React.ReactNode })
const language = getMarketplaceLanguage()
return (
<html lang={language} dir={language === 'ar' ? 'rtl' : 'ltr'} suppressHydrationWarning>
<head>
{/* Runs before hydration to prevent flash of wrong theme */}
<script
dangerouslySetInnerHTML={{
__html: `(function(){try{var t=document.cookie.split(';').map(function(c){return c.trim()}).find(function(c){return c.startsWith('rentaldrivego-theme=')});if(t)t=t.split('=')[1];if(!t)t=localStorage.getItem('rentaldrivego-theme');if(t==='dark'){document.documentElement.classList.add('dark');document.documentElement.style.colorScheme='dark';}}catch(e){}})()`,
}}
/>
</head>
<body suppressHydrationWarning>
<MarketplaceShell initialLanguage={language}>{children}</MarketplaceShell>
</body>
@@ -328,9 +328,12 @@ export default function MarketplaceShell({
useEffect(() => {
document.documentElement.classList.toggle('dark', theme === 'dark')
document.documentElement.style.colorScheme = theme === 'dark' ? 'dark' : 'light'
document.body.dataset.theme = theme
writeScopedPreference(SHARED_THEME_KEY, theme, ['marketplace-theme'])
}, [theme])
if (hydrated) {
writeScopedPreference(SHARED_THEME_KEY, theme, ['marketplace-theme'])
}
}, [theme, hydrated])
const value = useMemo(
() => ({ language, theme, dict: dictionaries[language], companyName, setLanguage: applyLanguage, setTheme: applyTheme }),