Skip to content

Instantly share code, notes, and snippets.

@cvan
Created July 1, 2020 20:15
Show Gist options
  • Save cvan/468b6ba4e070288106024735bdce2e37 to your computer and use it in GitHub Desktop.
Save cvan/468b6ba4e070288106024735bdce2e37 to your computer and use it in GitHub Desktop.
useMedia - React hook for `window.matchMedia` for matching media-query
function useMedia(mediaQuery) {
const match = () => {
if (!window.matchMedia) {
return false;
}
return window.matchMedia(mediaQuery).matches;
};
const [value, set] = useState(match);
useEffect(() => {
// Update state on window `resize` event.
// Usage of `match` function defined outside of `useEffect`
// ensures that it has current values of arguments.
const handler = () => set(match);
window.addEventListener('resize', handler);
// Remove event listener on cleanup.
return () => window.removeEventListener('resize', handler);
});
return value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment