Spaces:
Running
Running
import { useState, useEffect, useCallback, createContext, useContext } from 'react'; | |
// Create a context for theme | |
export const ThemeContext = createContext(); | |
export const useTheme = () => { | |
const context = useContext(ThemeContext); | |
if (!context) { | |
throw new Error('useTheme must be used within a ThemeProvider'); | |
} | |
return context; | |
}; | |
const useRawThemeState = () => { | |
const [isDark, setIsDark] = useState(() => { | |
// Check localStorage for saved preference | |
const savedMode = localStorage.getItem('themeMode'); | |
if (savedMode) return savedMode === 'dark'; | |
// Fallback to system preference | |
return window.matchMedia('(prefers-color-scheme: dark)').matches; | |
}); | |
// const [themeLoading, setThemeLoading] = useState(true); // Remove themeLoading state | |
useEffect(() => { | |
// Remove direct body class manipulation | |
// if (isDark) { | |
// document.body.classList.add('dark-mode'); | |
// document.body.classList.remove('light-mode'); | |
// } else { | |
// document.body.classList.add('light-mode'); | |
// document.body.classList.remove('dark-mode'); | |
// } | |
// Save preference to localStorage | |
localStorage.setItem('themeMode', isDark ? 'dark' : 'light'); | |
// setThemeLoading(false); // Remove themeLoading update | |
}, [isDark]); | |
const toggleTheme = useCallback(() => { | |
setIsDark(prev => !prev); | |
}, []); | |
// Return themeLoading as false or remove it completely if not used elsewhere | |
return { isDark, toggleTheme /*, themeLoading */}; | |
}; | |
// Theme provider component | |
export const ThemeProvider = ({ children }) => { | |
const themeState = useRawThemeState(); | |
return ( | |
<ThemeContext.Provider value={themeState}> | |
{children} | |
</ThemeContext.Provider> | |
); | |
}; | |
export default useRawThemeState; |