Skip to content

Instantly share code, notes, and snippets.

@petamoriken
Created June 20, 2020 15:24
Show Gist options
  • Save petamoriken/e2160be246cb4aa820883fe453c8588c to your computer and use it in GitHub Desktop.
Save petamoriken/e2160be246cb4aa820883fe453c8588c to your computer and use it in GitHub Desktop.
import { useEffect, useState } from "react";
/**
* @example
* const matches = useMatchMedia("screen and (min-width: 560px)");
*
* @param raw
*/
export function useMatchMedia(raw: string): boolean {
const [matches, setMatches] = useState(false);
useEffect(() => {
// eslint-disable-next-line no-undef
const query = matchMedia(raw);
setMatches(query.matches);
const handleChange = (e: MediaQueryListEvent): void => {
setMatches(e.matches);
};
// eslint-disable-next-line no-undef
if (query instanceof EventTarget) {
query.addEventListener("change", handleChange);
} else {
(query as MediaQueryList).addListener(handleChange);
}
return (): void => {
// eslint-disable-next-line no-undef
if (query instanceof EventTarget) {
query.removeEventListener("change", handleChange);
} else {
(query as MediaQueryList).removeListener(handleChange);
}
};
}, [raw]);
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment