Skip to content

Instantly share code, notes, and snippets.

@PuruVJ
Created April 6, 2021 11:30
Show Gist options
  • Save PuruVJ/d15bf536ce9b75626ca6c45d13886215 to your computer and use it in GitHub Desktop.
Save PuruVJ/d15bf536ce9b75626ca6c45d13886215 to your computer and use it in GitHub Desktop.
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