Use `prefers-color-scheme` preference over localStorage color mode
See original GitHub issueDescribe the bug
When toggling between light/dark mode on a supoprted device (in this case iOS, or MacOS via Firefox), Theme-UI’s color scheme does not update. Updating the app to reflect the user’s color mode requires the localstorage to be deleted.
but may I add, setting up dark/light mode in it’s current state has been an absolute breeze - thank you!
To Reproduce Steps to reproduce the behavior:
- Follow steps outlined in https://theme-ui.com/color-modes/
- Clear local storage and refresh
- App should render with your system preferences
- Try toggling between light/dark mode in your system preferences and watch the behaviour of the app.
Expected behavior
As I’ve enabled useColorSchemeMediaQuery
, I would expect the color modes to behave as a media query (in other words, on user-agent change - much like a breakpoint).
Screenshots
An example in Theme-UI: (using useColorSchemeMediaQuery
)
Examples of ‘expected behaviour’ in non-Theme-UI applications
Additional context Related issues: https://github.com/system-ui/theme-ui/issues/367
Issue Analytics
- State:
- Created 3 years ago
- Reactions:4
- Comments:7 (3 by maintainers)
Top GitHub Comments
I agree, this would be awesome.
As a supplement, I went ahead and created a workaround to automatically update (and override) the color mode when the
prefers-color-scheme
media-query changes.Feel free to use this for the time being if it’s helpful.
useEffect(() => {
const switchMode = e => {
const isDarkMode = e.matches
isDarkMode ? setMode("dark") : setMode("light")
}
const darkModeMediaQuery = window.matchMedia("(prefers-color-scheme: dark)")
darkModeMediaQuery.addListener(switchMode)
}, [setMode])
That said, something I have noticed (and I’m not sure if this is the case for those using Gatsby), but when a default theme is set and
useColorSchemeMediaQuery
istrue
, I still seem to get a flicker from light to dark upon first load whenprefers-color-scheme: dark
— for reference, this happens with the Gatsby package installed…This issue happens when visiting the page for the first time, I’m assuming it may be due to the color mode method initially looking for a stored value in local storage? Could there be a better way to prevent this from happening?
Extending on @dannykeane’s snippet I think it should cleanup on unmount
Please correct me if I’m wrong