Skip to content

Instantly share code, notes, and snippets.

@tannerlinsley
Last active June 4, 2021 17:24
Show Gist options
  • Save tannerlinsley/758aeefa6ec6593ce7f6c385d2204d55 to your computer and use it in GitHub Desktop.
Save tannerlinsley/758aeefa6ec6593ce7f6c385d2204d55 to your computer and use it in GitHub Desktop.
import React from 'react'
export default function useDarkMode({
intervalTime = 300,
getIsDark = defaultGetIsDark,
} = {}) {
// Keep track of the current mode
const [isDark, setIsDark] = React.useState(() => getIsDark())
// Set up the checker
React.useEffect(() => {
const interval = setInterval(() => {
const newIsDark = getIsDark()
// If the user's preference has changed
if (isDark !== newIsDark) {
// Update!
setIsDark(newIsDark)
}
}, intervalTime)
return () => {
clearInterval(interval)
}
}, [getIsDark, intervalTime, isDark, setIsDark])
return isDark
}
function defaultGetIsDark() {
// The defualt checker uses matchMedia :)
return (
window.matchMedia &&
window.matchMedia('(prefers-color-scheme: dark)').matches
)
}
// Usage
function App() {
const userPrefersDarkMode = useDarkMode()
//
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment