Skip to content

Instantly share code, notes, and snippets.

@bintangmuh
Last active August 11, 2021 11:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bintangmuh/0b67c253211b4ac2c5baf04cfba5989c to your computer and use it in GitHub Desktop.
Save bintangmuh/0b67c253211b4ac2c5baf04cfba5989c to your computer and use it in GitHub Desktop.
Dark Theme Hooks with Local Storage for Tailwind css
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