Last active
June 4, 2021 17:24
-
-
Save tannerlinsley/758aeefa6ec6593ce7f6c385d2204d55 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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