created at 2023/06/01 12:56:10
updated at 2023/06/01 12:56:16
TypeScript
import { useEffect, useState } from "react";
export default function usePrefersDarkMode(defaultValue: boolean) {
const [value, setValue] = useState(() => defaultValue);
useEffect(() => {
if (typeof window !== "undefined") {
const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");
setValue(mediaQuery.matches);
const handler = () => setValue(mediaQuery.matches);
mediaQuery.addEventListener("change", handler);
return () => mediaQuery.removeEventListener("change", handler);
}
}, []);
return value;
}