fix(seo): resolve theme SSR/hydration mismatch (React error #418)
useTheme's initial state now always renders 'light' on both server and client's first render pass, matching exactly. The real stored/OS-preferred theme is applied afterward in an effect (runs only post-hydration), instead of computing it during the initializer, which returned different values between the server (no window) and a client whose actual localStorage/ matchMedia preference differed from the SSR default (e.g. dark-mode OS or a stored 'dark' preference) — a real hydration mismatch on the ThemeToggle's rendered icon and aria-pressed attribute, intermittent per visitor/system.
This commit is contained in:
@@ -2,15 +2,22 @@ import { useEffect, useState } from 'react';
|
|||||||
|
|
||||||
const STORAGE_KEY = 'theme';
|
const STORAGE_KEY = 'theme';
|
||||||
|
|
||||||
function getInitialTheme() {
|
function readStoredOrPreferredTheme() {
|
||||||
if (typeof window === 'undefined') return 'light';
|
|
||||||
const stored = localStorage.getItem(STORAGE_KEY);
|
const stored = localStorage.getItem(STORAGE_KEY);
|
||||||
if (stored === 'light' || stored === 'dark') return stored;
|
if (stored === 'light' || stored === 'dark') return stored;
|
||||||
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function useTheme() {
|
export function useTheme() {
|
||||||
const [theme, setTheme] = useState(getInitialTheme);
|
const [theme, setTheme] = useState('light');
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const preferred = readStoredOrPreferredTheme();
|
||||||
|
if (preferred !== theme) {
|
||||||
|
setTheme(preferred);
|
||||||
|
}
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.documentElement.setAttribute('data-theme', theme);
|
document.documentElement.setAttribute('data-theme', theme);
|
||||||
|
|||||||
Reference in New Issue
Block a user