-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paththeme-context.tsx
70 lines (56 loc) · 1.57 KB
/
theme-context.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
'use client';
import React, { useEffect, useState, createContext, useContext } from 'react';
type Theme = 'light' | 'dark';
type ThemeContextProviderProps = {
children: React.ReactNode;
};
type ThemeContextType = {
theme: Theme;
toggleTheme: () => void;
};
const ThemeContext = createContext<ThemeContextType | null>(null);
export default function ThemeContextProvider({
children,
}: ThemeContextProviderProps) {
const [theme, setTheme] = useState<Theme>('light');
const toggleTheme = () => {
if (theme === 'light') {
setTheme('dark');
window.localStorage.setItem('theme', 'dark');
document.documentElement.classList.add('dark');
} else {
setTheme('light');
window.localStorage.setItem('theme', 'light');
document.documentElement.classList.remove('dark');
}
};
useEffect(() => {
const localTheme = window.localStorage.getItem('theme') as Theme | null;
if (localTheme) {
setTheme(localTheme);
if (localTheme === 'dark') {
document.documentElement.classList.add('dark');
}
} else if (window.matchMedia('(prefers-color-scheme: dark)').matches) {
setTheme('dark');
document.documentElement.classList.add('dark');
}
}, []);
return (
<ThemeContext.Provider
value={{
theme,
toggleTheme,
}}
>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const context = useContext(ThemeContext);
if (context === null) {
throw new Error('useTheme must be used within a ThemeContextProvider');
}
return context;
}