Skip to content

Instantly share code, notes, and snippets.

@byurhannurula
Created October 30, 2020 11:42
Show Gist options
  • Save byurhannurula/7d3242817a588e06ff157b04c83b51a2 to your computer and use it in GitHub Desktop.
Save byurhannurula/7d3242817a588e06ff157b04c83b51a2 to your computer and use it in GitHub Desktop.
React.js hook for light/dark theme
import { useState, useEffect } from 'react'
export const useColorMode = () => {
const [theme, setTheme] = useState(
window.localStorage.getItem('theme') || 'light',
)
const setNewTheme = (newTheme) => {
setTheme(newTheme)
window.localStorage.setItem('theme', newTheme)
document.documentElement.setAttribute('data-theme', newTheme)
}
const toggleTheme = () => {
if (theme === 'dark') {
setNewTheme('light')
} else {
setNewTheme('dark')
}
}
const prefersDarkMode = () => {
const query = window.matchMedia('(prefers-color-scheme: dark)')
if (query !== 'undefined' && query.matches) {
return true
}
return false
}
useEffect(() => {
const localTheme = window.localStorage.getItem('theme')
if (localTheme) {
setNewTheme(localTheme)
} else if (prefersDarkMode()) {
setNewTheme('dark')
} else {
setNewTheme('light')
}
}, [])
return [theme, toggleTheme]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment