Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 2x 15x 8x 15x 8x 8x 8x 4x 8x 8x 15x 12x 4x 8x | import { useLayoutEffect, useEffect, useState } from 'react';
/**
* Custom hook to detect and manage dark mode based on system preference.
* Automatically applies/removes the 'dark' class to the document root.
*/
export const useDarkMode = (): void => {
const [isDarkMode, setIsDarkMode] = useState(
() => window.matchMedia('(prefers-color-scheme: dark)').matches,
);
// Check system preference for dark mode
useLayoutEffect(() => {
const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
setIsDarkMode(mediaQuery.matches);
const handleChange = (event: MediaQueryListEvent): void => {
setIsDarkMode(event.matches);
};
mediaQuery.addEventListener('change', handleChange);
return () => mediaQuery.removeEventListener('change', handleChange);
}, []);
// Apply dark mode class to document
useEffect(() => {
if (isDarkMode) {
document.documentElement.classList.add('dark');
} else {
document.documentElement.classList.remove('dark');
}
}, [isDarkMode]);
};
|