fix(react): resolve theme toggle hydration mismatch - #1103
puneetnith28 wants to merge 3 commits into
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Please review this PR and let me know if any further changes are needed. |
| useEffect(() => { | ||
| const stored = localStorage.getItem('theme'); | ||
| if (stored) { | ||
| setPref(stored); | ||
| } | ||
| }, []); |
There was a problem hiding this comment.
| useEffect(() => { | |
| const stored = localStorage.getItem('theme'); | |
| if (stored) { | |
| setPref(stored); | |
| } | |
| }, []); | |
| useEffect(() => { | |
| const stored = localStorage.getItem('theme'); | |
| if (stored === 'light' || stored === 'dark') { | |
| setPref(stored); | |
| } | |
| }, []); |
There was a problem hiding this comment.
we dont need to reapply system
There was a problem hiding this comment.
wouldn’t stored !== pref be a little more robust?
There was a problem hiding this comment.
if somehow stored is returned as null, its better to check explicitly. WDYT?
There was a problem hiding this comment.
Updated to explicitly check for 'light' or 'dark' to safely handle null and avoid re-applying system.
Thanks for suggestion !!
| <ThemeToggle | ||
| onChange={setThemePreference} | ||
| currentTheme={themePreference} | ||
| key={themePreference} |
There was a problem hiding this comment.
why we need key here? without this , it seems to fix the icon just the same
There was a problem hiding this comment.
I added key thinking a remount might be needed, but currentTheme prop updates already handle the re-render properly
|
LGTM ! |
Description
Fixes a hydration mismatch where the
ThemeToggleicon resets to thesystemicon after page reload when a user preference (dark/light) is stored.Changes
prefstate to'system'by default inuseTheme.mjsto ensure server HTML and client initial render match.prefwithlocalStorageinside auseEffecthook on client mount.key={themePreference}to<ThemeToggle>to ensure clean remounting when the theme preference is applied.References