Fix theme hydration mismatch - #58
Merged
Merged
Conversation
The hook initialised state from localStorage and matchMedia during the first client render, so the server-rendered sun icon could differ from the client's moon icon and React reported a hydration error on every page. The pre-hydration script already puts the theme class on the html element, so the hook now treats that class as the single source of truth through useSyncExternalStore, rendering light on the server and reading the real theme once hydrated.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
React reported error 418 (text hydration mismatch) on every page.
useThemeinitialised its state from localStorage and matchMedia during the first client render, so the server-rendered ☀️ could differ from the client's 🌙.Fix
The pre-hydration
ThemeScriptalready puts thelight/darkclass on thehtmlelement before React runs. The hook now treats that class as the single source of truth viauseSyncExternalStore: it renderslighton the server, reads the real class once hydrated, and follows later class changes through a MutationObserver. Toggling writes the class and localStorage directly.Theme resolution logic (stored preference, then system preference) now lives only in
ThemeScript.Verification
theme=darkstored: no console errors on load, moon icon shown, toggle works both ways and persists🤖 Generated with Claude Code