--- title: Prevent Hydration Mismatch Without Flickering impact: MEDIUM impactDescription: avoids visual flicker and hydration errors tags: rendering, ssr, hydration, localStorage, flicker --- ## Prevent Hydration Mismatch Without Flickering When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates. **Incorrect (breaks SSR):** ```tsx function ThemeWrapper({ children }: { children: ReactNode }) { // localStorage is not available on server - throws error const theme = localStorage.getItem('theme') || 'light' return (
{children}
) } ``` Server-side rendering will fail because `localStorage` is undefined. **Incorrect (visual flickering):** ```tsx function ThemeWrapper({ children }: { children: ReactNode }) { const [theme, setTheme] = useState('light') useEffect(() => { // Runs after hydration - causes visible flash const stored = localStorage.getItem('theme') if (stored) { setTheme(stored) } }, []) return (
{children}
) } ``` Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content. **Correct (no flicker, no hydration mismatch):** ```tsx function ThemeWrapper({ children }: { children: ReactNode }) { return ( <>
{children}