Files
sam-react-prod/src/contexts/ThemeContext.tsx

55 lines
1.3 KiB
TypeScript
Raw Normal View History

"use client";
import { createContext, useContext, useState, useEffect, ReactNode } from "react";
type Theme = "light" | "dark" | "senior";
interface ThemeContextType {
theme: Theme;
setTheme: (theme: Theme) => void;
}
const ThemeContext = createContext<ThemeContextType | undefined>(undefined);
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setThemeState] = useState<Theme>("light");
useEffect(() => {
// Load theme from localStorage on mount
const savedTheme = localStorage.getItem("theme") as Theme;
if (savedTheme) {
setThemeState(savedTheme);
applyTheme(savedTheme);
}
}, []);
const setTheme = (newTheme: Theme) => {
setThemeState(newTheme);
localStorage.setItem("theme", newTheme);
applyTheme(newTheme);
};
const applyTheme = (theme: Theme) => {
const root = document.documentElement;
// Remove all theme classes
root.classList.remove("light", "dark", "senior");
// Add new theme class
root.classList.add(theme);
};
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
export function useTheme() {
const context = useContext(ThemeContext);
if (context === undefined) {
throw new Error("useTheme must be used within a ThemeProvider");
}
return context;
}