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