42 lines
914 B
JavaScript
42 lines
914 B
JavaScript
import React, { createContext, useContext, useState, useEffect } from 'react';
|
|
|
|
const ThemeContext = createContext();
|
|
|
|
export const useTheme = () => {
|
|
const context = useContext(ThemeContext);
|
|
if (!context) {
|
|
throw new Error('useTheme must be used within a ThemeProvider');
|
|
}
|
|
return context;
|
|
};
|
|
|
|
export const ThemeProvider = ({ children }) => {
|
|
const [theme, setTheme] = useState('light');
|
|
|
|
useEffect(() => {
|
|
const savedTheme = localStorage.getItem('theme');
|
|
if (savedTheme) {
|
|
setTheme(savedTheme);
|
|
}
|
|
}, []);
|
|
|
|
const toggleTheme = () => {
|
|
const newTheme = theme === 'light' ? 'dark' : 'light';
|
|
setTheme(newTheme);
|
|
localStorage.setItem('theme', newTheme);
|
|
};
|
|
|
|
const value = {
|
|
theme,
|
|
toggleTheme,
|
|
};
|
|
|
|
return (
|
|
<ThemeContext.Provider value={value}>
|
|
<div className={theme}>
|
|
{children}
|
|
</div>
|
|
</ThemeContext.Provider>
|
|
);
|
|
};
|