Last active
August 11, 2021 11:10
-
-
Save bintangmuh/0b67c253211b4ac2c5baf04cfba5989c to your computer and use it in GitHub Desktop.
Dark Theme Hooks with Local Storage for Tailwind css
This file contains 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 { useEffect, useState } from "react" | |
export function useToggleTheme() { | |
const [theme, setTheme] = useState('dark') | |
useEffect(() => { | |
if (localStorage.theme === 'dark' || (!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: dark)').matches)) { | |
document.documentElement.classList.add('dark') | |
setTheme('dark') | |
} else { | |
document.documentElement.classList.remove('dark') | |
setTheme('light') | |
} | |
return null; | |
}, [theme]) | |
function changeThemeMode() { | |
let mode = '' | |
if (theme === "light") { | |
mode = 'dark' | |
} else { | |
mode = 'light' | |
} | |
setTheme(mode) | |
localStorage.setItem('theme', mode) | |
} | |
return [theme, changeThemeMode] | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment