Files
rxminder/hooks/useTheme.ts
William Valentin e48adbcb00 Initial commit: Complete NodeJS-native setup
- Migrated from Python pre-commit to NodeJS-native solution
- Reorganized documentation structure
- Set up Husky + lint-staged for efficient pre-commit hooks
- Fixed Dockerfile healthcheck issue
- Added comprehensive documentation index
2025-09-06 01:42:48 -07:00

44 lines
1.3 KiB
TypeScript

import { useEffect, useMemo } from 'react';
import { useLocalStorage } from './useLocalStorage';
type Theme = 'light' | 'dark' | 'system';
export function useTheme() {
const [theme, setTheme] = useLocalStorage<Theme>('theme', 'system');
const systemTheme = useMemo(() => {
if (typeof window !== 'undefined' && window.matchMedia) {
return window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light';
}
return 'light';
}, []);
const applyTheme = () => {
const themeToApply = theme === 'system' ? systemTheme : theme;
const root = window.document.documentElement;
root.classList.remove('light', 'dark');
root.classList.add(themeToApply);
};
useEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
const handleChange = () => {
if (theme === 'system') {
applyTheme();
}
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [theme]);
useEffect(() => {
applyTheme();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [theme, systemTheme]);
return { theme, setTheme };
}