Skip to content

Instantly share code, notes, and snippets.

@giuseppeg
Last active April 12, 2020 19:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save giuseppeg/a9319fc63ef3d91012582db418982c5d to your computer and use it in GitHub Desktop.
Save giuseppeg/a9319fc63ef3d91012582db418982c5d to your computer and use it in GitHub Desktop.
Note this is a proof of concept and probably there are corner cases that I haven't considered. https://twitter.com/pacocoursey/status/1249226550756573184
let currentTheme = 'light'
const broadcastThemeChangeFunctions = new Set()
let media = null
function listener(media) {
currentTheme = themes[media.matches ? 'dark' : 'light']
for (let setTheme of broadcastThemeChangeFunctions) {
setTheme(currentTheme)
}
}
function useSystemTheme() {
const [theme, setTheme] = React.useState(themes[currentTheme])
React.useEffect(() => {
broadcastThemeChangeFunctions.add(setTheme)
if (!media) {
media = window.matchMedia('(prefers-color-scheme: dark)')
media.addEventListener(listener)
listener(media)
}
return () => {
broadcastThemeChangeFunctions.delete(setTheme)
if (broadcastThemeChangeFunctions.size == 0 && media) {
// remove event listener too
media = null
}
}
}, [])
return theme
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment