| import { createContext, useContext, useState, useEffect } from 'react' | |
| const ThemeContext = createContext() | |
| export function ThemeProvider({ children }) { | |
| const [theme, setTheme] = useState('light') | |
| useEffect(() => { | |
| const savedTheme = localStorage.getItem('theme') || 'light' | |
| setTheme(savedTheme) | |
| if (savedTheme === 'dark') { | |
| document.documentElement.classList.add('dark') | |
| } | |
| }, []) | |
| const toggleTheme = () => { | |
| const newTheme = theme === 'light' ? 'dark' : 'light' | |
| setTheme(newTheme) | |
| localStorage.setItem('theme', newTheme) | |
| if (newTheme === 'dark') { | |
| document.documentElement.classList.add('dark') | |
| } else { | |
| document.documentElement.classList.remove('dark') | |
| } | |
| } | |
| return ( | |
| <ThemeContext.Provider value={{ theme, toggleTheme }}> | |
| {children} | |
| </ThemeContext.Provider> | |
| ) | |
| } | |
| export function useTheme() { | |
| const context = useContext(ThemeContext) | |
| if (!context) { | |
| throw new Error('useTheme must be used within ThemeProvider') | |
| } | |
| return context | |
| } |