25 lines
830 B
TypeScript
25 lines
830 B
TypeScript
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;
|
||
|
|
}
|