24 lines
712 B
TypeScript
24 lines
712 B
TypeScript
import { useEffect, useState } from "react";
|
|
|
|
export type Theme = "light" | "dark";
|
|
|
|
export function useTheme() {
|
|
const [theme, setTheme] = useState<Theme>(() => {
|
|
const saved = localStorage.getItem("theme") as Theme | null;
|
|
if (saved === "light" || saved === "dark") return saved;
|
|
const isDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
|
|
return isDark ? "dark" : "light";
|
|
});
|
|
|
|
useEffect(() => {
|
|
document.documentElement.setAttribute("data-theme", theme);
|
|
localStorage.setItem("theme", theme);
|
|
}, [theme]);
|
|
|
|
const toggleTheme = () => {
|
|
setTheme((prev) => (prev === "light" ? "dark" : "light"));
|
|
};
|
|
|
|
return { theme, toggleTheme };
|
|
}
|