Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
File size: 855 Bytes
e7abd9e |
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 |
import { useState, useEffect } from 'react';
export const useThemeMode = () => {
// Get system preference
const getSystemPreference = () => {
return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
};
// Initialize theme mode from system preference
const [mode, setMode] = useState(getSystemPreference);
// Listen to system preference changes
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = (e) => {
setMode(e.matches ? 'dark' : 'light');
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, []);
const toggleTheme = () => {
setMode((prevMode) => (prevMode === 'light' ? 'dark' : 'light'));
};
return { mode, toggleTheme };
}; |