Last active
April 12, 2020 19:13
-
-
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
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
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