-
Notifications
You must be signed in to change notification settings - Fork 175
/
theme.tsx
35 lines (27 loc) · 928 Bytes
/
theme.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import * as React from 'react';
export const THEME_KEY = 'theme';
export enum Theme {
Dark = 'dark',
Light = 'light',
}
const init = (JSON.parse(window.localStorage.getItem(THEME_KEY)) as Theme) || Theme.Light;
interface ThemeContextProps {
theme: Theme;
set: (th: Theme) => void;
}
export const ThemeContext = React.createContext({theme: init} as ThemeContextProps);
export const ThemeProvider = (props: {children: React.ReactNode}) => {
const [theme, setTheme] = React.useState(init);
React.useEffect(() => {
window.localStorage.setItem(THEME_KEY, JSON.stringify(theme));
}, [theme]);
return <ThemeContext.Provider value={{theme, set: (th) => setTheme(th)}}>{props.children}</ThemeContext.Provider>;
};
export const useTheme = () => {
try {
const dmCtx = React.useContext(ThemeContext);
return dmCtx.theme;
} catch {
return Theme.Light;
}
};