Files
cinny/src/app/hooks/useMediaQuery.ts
T

25 lines
830 B
TypeScript
Raw Normal View History

import { useEffect, useState } from 'react';
const read = (query: string): boolean =>
typeof window !== 'undefined' &&
typeof window.matchMedia === 'function' &&
window.matchMedia(query).matches;
/** Reactive `window.matchMedia(query).matches`. SSR-safe (false). */
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState<boolean>(() => read(query));
useEffect(() => {
if (typeof window === 'undefined' || typeof window.matchMedia !== 'function') {
return undefined;
}
const mql = window.matchMedia(query);
const onChange = (event: MediaQueryListEvent) => setMatches(event.matches);
setMatches(mql.matches);
mql.addEventListener('change', onChange);
return () => mql.removeEventListener('change', onChange);
}, [query]);
return matches;
}