04c33cb1aa
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
21 lines
582 B
TypeScript
21 lines
582 B
TypeScript
import { useEffect, useState } from "react";
|
|
|
|
/** SSR-safe `matchMedia` subscription; `true` while `query` matches. */
|
|
export function useMediaQuery(query: string): boolean {
|
|
const [matches, setMatches] = useState(() =>
|
|
typeof window !== "undefined" ? window.matchMedia(query).matches : false,
|
|
);
|
|
|
|
useEffect(() => {
|
|
const mql = window.matchMedia(query);
|
|
const onChange = () => setMatches(mql.matches);
|
|
|
|
onChange();
|
|
mql.addEventListener("change", onChange);
|
|
|
|
return () => mql.removeEventListener("change", onChange);
|
|
}, [query]);
|
|
|
|
return matches;
|
|
}
|