niels segers

use-theme

A hook to toggle between light and dark mode (tailwind). It uses localForage to store the user preference.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 import { useEffect } from 'react'; import useLocalForage from './use-local-forage'; export default function useTheme() { const [theme, setTheme] = useLocalForage('theme', 'light'); useEffect(() => { const htmlElement = document.documentElement; if (theme === 'dark') { htmlElement.classList.add('dark'); } else { htmlElement.classList.remove('dark'); } }, [theme]); const toggle = () => { setTheme(theme === 'dark' ? 'light' : 'dark'); }; return { theme, toggle, }; }