Skip to content

Instantly share code, notes, and snippets.

@freddi301
Created October 11, 2019 09:56
Show Gist options
  • Save freddi301/6b210f6a077b58f30cd5579bfc2c9cbe to your computer and use it in GitHub Desktop.
Save freddi301/6b210f6a077b58f30cd5579bfc2c9cbe to your computer and use it in GitHub Desktop.
useMediaQuery #react #hook
import React from "react";
/**
* Matches mediaquery, rerenders only when match changes
* @param query media query
*/
export function useMediaQuery(
query: string | null | false,
defValue: boolean = false,
) {
const [matches, setMatches] = React.useState(() =>
query ? window.matchMedia(query).matches : defValue,
);
React.useEffect(() => {
if (!query) {
return undefined;
}
let ignore = false;
const mql = window.matchMedia(query);
function onChange() {
if (!ignore) {
setMatches(mql.matches);
}
}
mql.addListener(onChange);
setMatches(mql.matches);
return () => {
ignore = true;
mql.removeListener(onChange);
};
}, [query]);
return matches;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment