Skip to content

Instantly share code, notes, and snippets.

@donaldpipowitch
Last active February 10, 2023 17:48
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donaldpipowitch/b454bbfbc3c81a6708a915086cc0de31 to your computer and use it in GitHub Desktop.
Save donaldpipowitch/b454bbfbc3c81a6708a915086cc0de31 to your computer and use it in GitHub Desktop.
useMatchMedia - a React hook for matchMedia / media queries
import { useState, useEffect } from 'react';
// pass a query like `(min-width: 768px)`
export function useMatchMedia(query: string) {
const [matches, setMatches] = useState(() => matchMedia(query).matches);
useEffect(() => {
const mediaQueryList = matchMedia(query);
const onChange = (event: MediaQueryListEvent) => setMatches(event.matches);
// note 1: safari currently doesn't support add/removeEventListener so we use add/removeListener
// note 2: add/removeListener are maybe marked as deprecated, but that could be wrong
// see https://github.com/microsoft/TypeScript/issues/32210
mediaQueryList.addListener(onChange);
return () => mediaQueryList.removeListener(onChange);
}, [query]);
return matches;
}
@EliaECoyote
Copy link

While testing on safari i found out that addEventListener wasn't defined.
Perhaps this hook should use https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener instead

@donaldpipowitch
Copy link
Author

donaldpipowitch commented Jan 23, 2020

While testing on safari i found out that addEventListener wasn't defined.
Perhaps this hook should use https://developer.mozilla.org/en-US/docs/Web/API/MediaQueryList/addListener instead

Oh yeah, absolutely. Thanks for the ping. I'll update the Gist with the version we currently use in production.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment