-
-
Save jaabiri/4c678e045216b8623d3c12eddadfa157 to your computer and use it in GitHub Desktop.
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 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