Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
87 changes: 58 additions & 29 deletions src/components/ThemeProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,40 +12,68 @@ import {
type Theme = "light" | "dark";

interface ThemeContextValue {
theme: Theme;
// `theme` may be `undefined` on the first render (SSR) until we
// determine it on the client.
theme?: Theme;
toggleTheme: () => void;
setTheme: (theme: Theme) => void;
}

const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);

function getCurrentTheme(): Theme {
if (
typeof document !== "undefined" &&
document.documentElement.classList.contains("dark")
) {
return "dark";
}
return "light";
}

export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>(getCurrentTheme);
// Start uninitialized to avoid SSR/client mismatch. We will read
// the real theme on mount (client-only) and then sync state + DOM.
const [theme, setThemeState] = useState<Theme | undefined>(undefined);

const applyTheme = useCallback(
(next: Theme, persist = true) => {
setThemeState(next);
if (next === "dark") {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
if (persist) {
const applyTheme = useCallback((next: Theme, persist = true) => {
setThemeState(next);
if (next === "dark") {
document.documentElement.classList.add("dark");
} else {
document.documentElement.classList.remove("dark");
}
if (next === "high-contrast") {
document.documentElement.setAttribute("data-theme", "high-contrast");
} else {
document.documentElement.removeAttribute("data-theme");
}
if (persist) {
try {
localStorage.setItem("theme", next);
} catch {}
}
}, []);

// Client-only initialization: read localStorage or system preference
// and apply the theme. This avoids reading `document`/`localStorage`
// during SSR and prevents hydration mismatches.
useEffect(() => {
try {
const stored = localStorage.getItem("theme") as Theme | null;
if (stored === "light" || stored === "dark" || stored === "high-contrast") {
applyTheme(stored, false);
} else {
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
applyTheme(prefersDark ? "dark" : "light", false);
}
},
[]
);
} catch {
const prefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
applyTheme(prefersDark ? "dark" : "light", false);
}

// Listen for OS-level preference changes (only when no manual override)
const mq = window.matchMedia("(prefers-color-scheme: dark)");
const handler = (e: MediaQueryListEvent) => {
try {
if (!localStorage.getItem("theme")) {
applyTheme(e.matches ? "dark" : "light", false);
}
} catch {}
};
mq.addEventListener("change", handler);
return () => mq.removeEventListener("change", handler);
}, [applyTheme]);

useEffect(() => {
setThemeState(getCurrentTheme());
Expand All @@ -61,13 +89,14 @@ export function ThemeProvider({ children }: { children: ReactNode }) {
}, [applyTheme]);

const toggleTheme = useCallback(() => {
applyTheme(theme === "light" ? "dark" : "light");
// If theme is undefined (very early), default to light -> dark toggle
const current = theme ?? "light";
applyTheme(
current === "light" ? "dark" : current === "dark" ? "high-contrast" : "light"
);
}, [theme, applyTheme]);

const setTheme = useCallback(
(next: Theme) => applyTheme(next),
[applyTheme]
);
const setTheme = useCallback((next: Theme) => applyTheme(next), [applyTheme]);

return (
<ThemeContext.Provider value={{ theme, toggleTheme, setTheme }}>
Expand Down
4 changes: 3 additions & 1 deletion src/components/ThemeToggle.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ import { useTheme } from "./ThemeProvider";

export function ThemeToggle() {
const { theme, toggleTheme } = useTheme();
const isDark = theme === "dark";
// Avoid rendering until theme is initialized on the client to prevent
// SSR/client hydration mismatches and visible flicker.
if (theme === undefined) return null;

return (
<button
Expand Down
Loading