| 1 | --- |
| 2 | title: Prevent Hydration Mismatch Without Flickering |
| 3 | impact: MEDIUM |
| 4 | impactDescription: avoids visual flicker and hydration errors |
| 5 | tags: rendering, ssr, hydration, localStorage, flicker |
| 6 | --- |
| 7 | |
| 8 | ## Prevent Hydration Mismatch Without Flickering |
| 9 | |
| 10 | 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. |
| 11 | |
| 12 | **Incorrect (breaks SSR):** |
| 13 | |
| 14 | ```tsx |
| 15 | function ThemeWrapper({ children |
| 16 | // localStorage is not available on server - throws error |
| 17 | const theme = |
| 18 | |
| 19 | return <div className |
| 20 | } |
| 21 | ``` |
| 22 | |
| 23 | Server-side rendering will fail because `localStorage` is undefined. |
| 24 | |
| 25 | **Incorrect (visual flickering):** |
| 26 | |
| 27 | ```tsx |
| 28 | function ThemeWrapper({ children |
| 29 | const [theme, |
| 30 | |
| 31 | useEffect(() => |
| 32 | // Runs after hydration - causes visible flash |
| 33 | const stored = |
| 34 | if (stored) { |
| 35 | setTheme(stored); |
| 36 | } |
| 37 | }, []); |
| 38 | |
| 39 | return <div className |
| 40 | } |
| 41 | ``` |
| 42 | |
| 43 | Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content. |
| 44 | |
| 45 | **Correct (no flicker, no hydration mismatch):** |
| 46 | |
| 47 | ```tsx |
| 48 | function ThemeWrapper({ children |
| 49 | return ( |
| 50 | <> |
| 51 | <div id=" |
| 52 | <script |
| 53 | dangerouslySetInnerHTML={{ |
| 54 | __html: ` |
| 55 | (function() { |
| 56 | try { |
| 57 | var theme = localStorage.getItem('theme') || 'light'; |
| 58 | var el = document.getElementById('theme-wrapper'); |
| 59 | if (el) el.className = theme; |
| 60 | } catch (e) {} |
| 61 | })(); |
| 62 | `, |
| 63 | }} |
| 64 | /> |
| 65 | </> |
| 66 | ); |
| 67 | } |
| 68 | ``` |
| 69 | |
| 70 | The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch. |
| 71 | |
| 72 | This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values. |