Skip to content

Instantly share code, notes, and snippets.

@sean-clayton
Created August 26, 2019 15:53
Show Gist options
  • Save sean-clayton/a1dc4064e818d8d70bc24692ddd70f07 to your computer and use it in GitHub Desktop.
Save sean-clayton/a1dc4064e818d8d70bc24692ddd70f07 to your computer and use it in GitHub Desktop.
let useTheme = () => {
open ReactResponsiveRe;
open Dom.Storage;
open AppStyles;
open AppStyles.ThemeNames;
open AppStyles.ThemeStore;
let prefersDarkMode = useMediaQuery("(prefers-color-scheme: dark)");
let systemTheme =
switch (canAutoTheme) {
| false => ThemeNames.default
| _ => prefersDarkMode ? Dark : Light
};
let storedTheme = localStorage |> getItem("theme");
let initialThemeName =
Option.(storedTheme->flatMap(fromString)->getWithDefault(systemTheme));
let (state, dispatch) = store.useStore();
let {themeName} = state;
useOnMount(() => {
switch (initialThemeName) {
| Light => dispatch(SwitchToLightTheme)
| Dark => dispatch(SwitchToDarkTheme)
| Auto => dispatch(SwitchToAutoTheme)
};
None;
});
let set = t => {
localStorage |> setItem("theme", t->toString);
switch (t) {
| Auto => dispatch(SwitchToAutoTheme)
| Dark => dispatch(SwitchToDarkTheme)
| Light => dispatch(SwitchToLightTheme)
};
};
useEffect3(
() => {
switch (themeName, storedTheme, systemTheme) {
| (Auto, _, Light) => dispatch(AutoSwitchToLight)
| (Auto, _, Dark) => dispatch(AutoSwitchToDark)
| (_, None, _) => set(ThemeNames.default)
| _ => ()
};
None;
},
(themeName, storedTheme, systemTheme),
);
(state, set);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment