-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathThemeContext.tsx
48 lines (43 loc) · 910 Bytes
/
ThemeContext.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
36
37
38
39
40
41
42
43
44
45
46
47
48
import React, {
createContext,
useState,
useMemo,
Dispatch,
SetStateAction,
useEffect,
} from 'react';
interface ThemeContextType {
theme: boolean;
setTheme: Dispatch<SetStateAction<boolean>>;
}
export const ThemeContext = createContext<ThemeContextType>({
theme: false,
setTheme: () => {},
});
interface Props {
children: React.ReactNode;
}
export const ThemeProvider = ({ children }: Props) => {
const [theme, setTheme] = useState(false); // default is light
useEffect(() => {
const mode = localStorage.getItem('theme');
if (mode === 'true') {
setTheme(true);
}
if (mode === 'false') {
setTheme(false);
}
}, [theme]);
const contextValues = useMemo(
() => ({
theme,
setTheme,
}),
[theme, setTheme]
);
return (
<ThemeContext.Provider value={contextValues}>
{children}
</ThemeContext.Provider>
);
};