Skip to content

fix(web): resolve hydration mismatch in dark mode toggle#80

Open
mattheliu wants to merge 1 commit intoshareAI-lab:mainfrom
mattheliu:fix/hydration-dark-mode
Open

fix(web): resolve hydration mismatch in dark mode toggle#80
mattheliu wants to merge 1 commit intoshareAI-lab:mainfrom
mattheliu:fix/hydration-dark-mode

Conversation

@mattheliu
Copy link

Summary

  • Fix React hydration error in Header component caused by dark mode state diverging between server and client
  • useState initializer used typeof window !== 'undefined' branch which returns false on server but may return true on client (via localStorage / matchMedia), causing SSR HTML (Moon icon) to mismatch client (Sun icon)
  • Replace with static useState(false) + useEffect to defer theme detection until after hydration

Test plan

  • Run cd web && npm run dev, open in browser with dark mode system preference
  • Verify no hydration error in console
  • Verify dark/light toggle still works correctly
  • Verify theme persists across page refresh (localStorage)

🤖 Generated with Claude Code

The dark state was initialized via `typeof window !== 'undefined'` branch
inside useState, which returns different values on server (false) vs client
(reads localStorage/matchMedia). This caused a React hydration error because
the server-rendered Moon icon didn't match the client-rendered Sun icon.

Fix: initialize useState with a static `false` and defer the real theme
detection to a useEffect that runs after hydration.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant