50 lines
1.2 KiB
TypeScript
50 lines
1.2 KiB
TypeScript
'use client';
|
|
|
|
import { createContext, useContext, useEffect, useState } from 'react';
|
|
|
|
type Theme = 'light' | 'dark';
|
|
|
|
interface ThemeContextType {
|
|
theme: Theme;
|
|
toggleTheme: () => void;
|
|
}
|
|
|
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
|
|
|
export function ThemeProvider({ children }: { children: React.ReactNode }) {
|
|
const [theme, setTheme] = useState<Theme>('light');
|
|
|
|
useEffect(() => {
|
|
// Only use saved theme preference, otherwise default to light
|
|
const savedTheme = localStorage.getItem('theme') as Theme;
|
|
if (savedTheme) {
|
|
setTheme(savedTheme);
|
|
} else {
|
|
setTheme('light');
|
|
}
|
|
}, []);
|
|
|
|
useEffect(() => {
|
|
// Update document class and save preference
|
|
document.documentElement.classList.toggle('dark', theme === 'dark');
|
|
localStorage.setItem('theme', theme);
|
|
}, [theme]);
|
|
|
|
const toggleTheme = () => {
|
|
setTheme(prev => prev === 'light' ? 'dark' : 'light');
|
|
};
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
|
{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;
|
|
}
|