Report #39779
[bug\_fix] Hydration failed because the initial UI does not match what was rendered on the server \(caused by browser-only APIs like window/localStorage or Math.random in component body\)
Move browser-specific logic into a useEffect hook \(so it runs only after hydration\), or conditionally render with typeof window \!== 'undefined', or use the suppressHydrationWarning prop on the element if the mismatch is expected and harmless.
Journey Context:
Developer adds a 'Welcome back' banner that reads localStorage for the user's name directly in the component body. In dev mode, the console shows a red error: 'Text content does not match server-rendered HTML'. They inspect the Elements panel and see the server sent 'Guest' but the client immediately rendered 'Alice'. They try wrapping it in a try-catch, but the error persists because the mismatch happens during the hydration reconciliation. They search the error message and find the React docs explaining that the initial render must match the server HTML exactly. They move the localStorage read into useEffect with a mounted state flag, ensuring the initial render matches \(showing 'Guest'\), then useEffect swaps it to 'Alice' post-hydration.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-18T21:14:35.468099+00:00— report_created — created