Skip to content

fix: resolve hydration error in ThemeProvider#1

Open
EdgarMC100 wants to merge 1 commit intomainfrom
fix/hydration-error-theme-provider
Open

fix: resolve hydration error in ThemeProvider#1
EdgarMC100 wants to merge 1 commit intomainfrom
fix/hydration-error-theme-provider

Conversation

@EdgarMC100
Copy link
Copy Markdown
Owner

Summary

  • Fixed hydration error caused by server/client mismatch in ThemeProvider
  • Removed getInitial() function that returned different values on server vs client
  • Ensured consistent initial state ("dark") on both server and client
  • Added mount-only useEffect with ref guard to sync with actual DOM theme after hydration

Problem

The ThemeProvider was causing React hydration errors because:

  • Server: getInitial() always returned "dark" (document is undefined)
  • Client: getInitial() read from document.documentElement.dataset.theme (could be "light")
  • This mismatch caused React to detect that server-rendered HTML didn't match client-rendered output

Solution

  • Initialize theme state with constant "dark" on both server and client
  • Use useEffect to sync with actual DOM theme after component mounts (client-only)
  • Use isInitialized ref guard to prevent cascading renders
  • Preserves existing theme script functionality to prevent visual flash

Test plan

  • Dev server starts without errors
  • No hydration errors in browser console
  • Theme toggling works correctly
  • Theme persists across page reloads
  • No visual flash on page load

🤖 Generated with Claude Code

…SSR/client initial state

The ThemeProvider was causing hydration mismatches because getInitial() returned different values on server vs client:
- Server: always returned "dark" (document is undefined)
- Client: read from document.documentElement.dataset.theme (could be "light")

This mismatch triggered React hydration errors when the server-rendered HTML didn't match the client-rendered output.

Solution:
- Remove getInitial() function to eliminate the server/client divergence
- Initialize theme state with a constant "dark" value on both server and client
- Add a mount-only useEffect to sync with the actual DOM theme after hydration completes
- Use isInitialized ref guard to prevent cascading renders
- Preserves existing theme script functionality to prevent visual flash
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