umami/hooks/useTheme.js
2023-05-17 23:20:06 -07:00

39 lines
943 B
JavaScript

import { useEffect } from 'react';
import useStore, { setTheme } from 'store/app';
import { getItem, setItem } from 'next-basics';
import { THEME_CONFIG } from 'lib/constants';
const selector = state => state.theme;
export function useTheme() {
const defaultTheme =
typeof window !== 'undefined'
? window?.matchMedia('(prefers-color-scheme: dark)')?.matches
? 'dark'
: 'light'
: 'light';
const theme = useStore(selector) || getItem(THEME_CONFIG) || defaultTheme;
function saveTheme(value) {
setItem(THEME_CONFIG, value);
setTheme(value);
}
useEffect(() => {
document.body.setAttribute('data-theme', theme);
}, [theme]);
useEffect(() => {
const url = new URL(window?.location?.href);
const theme = url.searchParams.get('theme');
if (['light', 'dark'].includes(theme)) {
saveTheme(theme);
}
}, []);
return [theme, saveTheme];
}
export default useTheme;