Created
April 6, 2021 11:30
-
-
Save PuruVJ/d15bf536ce9b75626ca6c45d13886215 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useAtom } from 'jotai'; | |
import { useEffect, useLayoutEffect } from 'preact/hooks'; | |
import { themeAtom } from '__/stores/theme.store'; | |
type Theme = 'light' | 'dark'; | |
// This is needed here | |
let isFirstUpdate = true; | |
const localValue = localStorage.getItem<Theme>('theme:type'); | |
const systemTheme: Theme = matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'; | |
/** | |
* Sitewide theme | |
*/ | |
export function useTheme() { | |
const [theme, setTheme] = useAtom(themeAtom); | |
useEffect(() => { | |
setTheme(localValue || systemTheme); | |
}, []); | |
useLayoutEffect(() => { | |
// Needed, because without it, the theme after reload stays light only | |
if (isFirstUpdate) return void (isFirstUpdate = false); | |
localStorage.setItem('theme:type', theme); | |
document.body.dataset.theme = theme; | |
}, [theme]); | |
return [theme, setTheme] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment