Skip to content

Instantly share code, notes, and snippets.

@will-t-harris
Created October 30, 2020 07:40
Show Gist options
  • Save will-t-harris/d04b701ec8ba5047dd3bf40c7bda0104 to your computer and use it in GitHub Desktop.
Save will-t-harris/d04b701ec8ba5047dd3bf40c7bda0104 to your computer and use it in GitHub Desktop.
React useMediaQuery
/** Takes a media query and returns a boolean value for whether or not specified media query was hit.
* -- e.g. '(min-width: 567px)'
*/
export const useMediaQuery = (query: string): boolean => {
const mediaMatch: MediaQueryList = window.matchMedia(query);
const [matches, setMatches] = useState<boolean>(mediaMatch.matches);
useEffect(() => {
const handler = e => setMatches(e.matches);
mediaMatch.addEventListener('change', handler);
return () => mediaMatch.removeEventListener('change', handler);
});
return matches;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment