Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/wojtekmaj/react-hooks. A collection of React Hooks.
hooks react react-hooks
Something went wrong. Try again.
1.1 kB · 43 lines
TypeScript
at main
1234567891011121314151617181920212223242526272829303132333435363738394041424344import { useCallback, useEffect, useState } from 'react';
const isBrowser = typeof window !== 'undefined';
/** * Returns a flag which determines if the document matches the given media query string. * * @param {string} query Media query string * @returns {boolean | null} Whether the document matches the given media query string */export default function useMatchMedia(query: string): boolean | null { const [matches, setMatches] = useState<boolean | null>(() => isBrowser ? window.matchMedia(query).matches : null, );
const handleMql = useCallback((event: MediaQueryListEvent) => { setMatches(event.matches); }, []);
useEffect(() => { if (!isBrowser) { return undefined; }
const mql = window.matchMedia(query);
if (mql.addEventListener) { mql.addEventListener('change', handleMql);
return () => { mql.removeEventListener('change', handleMql); }; } else { mql.addListener(handleMql);
return () => { mql.removeListener(handleMql); }; } }, [query, handleMql]);
return matches;}