Spaces:
Running
Running
File size: 1,335 Bytes
9d1a465 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
'use client';
import { createContext, useContext, useEffect, useState } from 'react';
type DarkModeContextType = {
isDarkMode: boolean;
toggleDarkMode: () => void;
};
const DarkModeContext = createContext<DarkModeContextType | undefined>(undefined);
export function DarkModeProvider({ children }: { children: React.ReactNode }) {
const [isDarkMode, setIsDarkMode] = useState(false);
useEffect(() => {
// Check if user has dark mode preference
const isDark = localStorage.getItem('darkMode') === 'true';
setIsDarkMode(isDark);
if (isDark) {
document.documentElement.classList.add('dark');
}
}, []);
const toggleDarkMode = () => {
setIsDarkMode((prev) => {
const newValue = !prev;
localStorage.setItem('darkMode', String(newValue));
if (newValue) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
return newValue;
});
};
return (
<DarkModeContext.Provider value={{ isDarkMode, toggleDarkMode }}>
{children}
</DarkModeContext.Provider>
);
}
export function useDarkMode() {
const context = useContext(DarkModeContext);
if (context === undefined) {
throw new Error('useDarkMode must be used within a DarkModeProvider');
}
return context;
} |