46 lines
1.2 KiB
TypeScript
46 lines
1.2 KiB
TypeScript
import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
|
|
|
|
type Theme = 'light' | 'dark';
|
|
|
|
interface ThemeContextType {
|
|
theme: Theme;
|
|
toggleTheme: () => void;
|
|
}
|
|
|
|
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
|
|
|
|
export const ThemeProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
|
|
const [theme, setTheme] = useState<Theme>(() => {
|
|
const storedTheme = localStorage.getItem('theme');
|
|
if (storedTheme) {
|
|
return storedTheme as Theme;
|
|
}
|
|
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
|
});
|
|
|
|
useEffect(() => {
|
|
const root = window.document.documentElement;
|
|
root.classList.remove('light', 'dark');
|
|
root.classList.add(theme);
|
|
localStorage.setItem('theme', theme);
|
|
}, [theme]);
|
|
|
|
const toggleTheme = () => {
|
|
setTheme((prevTheme) => (prevTheme === 'light' ? 'dark' : 'light'));
|
|
};
|
|
|
|
return (
|
|
<ThemeContext.Provider value={{ theme, toggleTheme }}>
|
|
{children}
|
|
</ThemeContext.Provider>
|
|
);
|
|
};
|
|
|
|
export const useTheme = (): ThemeContextType => {
|
|
const context = useContext(ThemeContext);
|
|
if (!context) {
|
|
throw new Error('useTheme must be used within a ThemeProvider');
|
|
}
|
|
return context;
|
|
};
|