Hey is a decentralized and permissionless social media app built with Lens Protocol 馃尶
1import { Localstorage } from "@hey/data/storage";
2import {
3 createContext,
4 type ReactNode,
5 useCallback,
6 useContext,
7 useEffect,
8 useMemo,
9 useState
10} from "react";
11
12type Theme = "light" | "dark";
13interface ThemeContextValue {
14 theme: Theme;
15 toggleTheme: () => void;
16}
17
18const ThemeContext = createContext<ThemeContextValue | null>(null);
19
20interface ThemeProviderProps {
21 children: ReactNode;
22}
23
24export const ThemeProvider = ({ children }: ThemeProviderProps) => {
25 const [theme, setTheme] = useState<Theme>(() => {
26 const saved = localStorage.getItem(Localstorage.Theme);
27 return (saved ?? "light") as Theme;
28 });
29
30 useEffect(() => {
31 document.documentElement.setAttribute("class", theme);
32 localStorage.setItem(Localstorage.Theme, theme);
33 }, [theme]);
34
35 const toggleTheme = useCallback(
36 () => setTheme((t) => (t === "light" ? "dark" : "light")),
37 []
38 );
39
40 const value = useMemo(() => ({ theme, toggleTheme }), [theme, toggleTheme]);
41
42 return (
43 <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>
44 );
45};
46
47export const useTheme = (): ThemeContextValue => {
48 const context = useContext(ThemeContext);
49 if (!context) {
50 throw new Error("useTheme must be used within a ThemeProvider");
51 }
52 return context;
53};