'use client';
import { createContext, useContext, useEffect, useState } from 'react';
type Theme = 'light' | 'dark';
interface ThemeContextType {
theme: Theme;
setTheme: (theme: Theme) => void;
resolvedTheme: 'light' | 'dark';
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
export function ThemeProvider({ children }: { children: React.ReactNode }) {
const [theme, setTheme] = useState<Theme>('light');
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
const stored = localStorage.getItem('theme') as Theme | null;
if (stored && (stored === 'light' || stored === 'dark')) {
setTheme(stored);
}
}, []);
useEffect(() => {
if (!mounted) return;
const root = document.documentElement;
if (theme === 'dark') {
root.classList.add('dark');
} else {
root.classList.remove('dark');
}
}, [theme, mounted]);
useEffect(() => {
if (mounted) {
localStorage.setItem('theme', theme);
}
}, [theme, mounted]);
// Prevent flash of incorrect theme
if (!mounted) {
return (
<ThemeContext.Provider value={{ theme: 'light', setTheme: () => {}, resolvedTheme: 'light' }}>
{children}
</ThemeContext.Provider>
);
}
return (
<ThemeContext.Provider value={{ theme, setTheme, resolvedTheme: theme }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error('useTheme must be used within a ThemeProvider');
}
return context;
}