Skip to content

Instantly share code, notes, and snippets.

@djanowski
Created December 1, 2021 20:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djanowski/2fd49dcf4c0acc5ff7bada44ea26b935 to your computer and use it in GitHub Desktop.
Save djanowski/2fd49dcf4c0acc5ff7bada44ea26b935 to your computer and use it in GitHub Desktop.
function useMatchMedia(query) {
const mediaQuery = useMemo(() => window.matchMedia(query), [ query ]);
const [ matches, setMatches ] = useState(mediaQuery.matches);
useEffect(() => {
function onChange({ matches: newMatches }) {
setMatches(newMatches);
}
if (mediaQuery.addEventListener)
mediaQuery.addEventListener('change', onChange);
else
mediaQuery.addListener(onChange);
return () => {
if (mediaQuery.removeEventListener)
mediaQuery.removeEventListener('change', onChange);
else
mediaQuery.removeListener(onChange);
};
}, [ mediaQuery ]);
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment