Skip to content

Commit 726f9b1

Browse files
committed
chore: add theme context
1 parent aaa7ac4 commit 726f9b1

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import { createContext, useContext, useEffect, useState } from "react";
2+
3+
type Theme = "light" | "dark";
4+
5+
interface ThemeContextType {
6+
theme: Theme;
7+
toggleTheme: () => void;
8+
}
9+
10+
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
11+
12+
export function ThemeProvider({ children }: { children: React.ReactNode }) {
13+
14+
const [theme, setTheme] = useState<Theme>(() => {
15+
const stored = localStorage.getItem("theme") as Theme | null;
16+
if (stored) return stored;
17+
18+
19+
if (window.matchMedia("(prefers-color-scheme: dark)").matches) { // Find system Preference
20+
return "dark";
21+
}
22+
return "light";
23+
});
24+
25+
26+
useEffect(() => {
27+
const root = document.documentElement;
28+
if (theme === "dark") {
29+
root.classList.add("dark");
30+
} else {
31+
root.classList.remove("dark");
32+
}
33+
localStorage.setItem("theme", theme);
34+
}, [theme]);
35+
36+
const toggleTheme = () => {
37+
setTheme((prev) => (prev === "light" ? "dark" : "light"));
38+
};
39+
40+
return (
41+
<ThemeContext.Provider value={{ theme, toggleTheme }}>
42+
{children}
43+
</ThemeContext.Provider>
44+
);
45+
}
46+
47+
export function useTheme() {
48+
const context = useContext(ThemeContext);
49+
if (!context) {
50+
throw new Error("useTheme must be used within ThemeProvider");
51+
}
52+
return context;
53+
}

0 commit comments

Comments
 (0)