Skip to content

Instantly share code, notes, and snippets.

@richcsmith
Last active June 14, 2022 17:17
Show Gist options
  • Save richcsmith/d8a48635636ba735467b44bf51be43f3 to your computer and use it in GitHub Desktop.
Save richcsmith/d8a48635636ba735467b44bf51be43f3 to your computer and use it in GitHub Desktop.
React/TypeScript Media Query Hook
import { useCallback, useEffect } from 'react';
export type MediaQuery = MediaQueryListEvent['media'];
export type MediaQueryCallback = (event: MediaQueryListEvent) => void;
export function useMediaQuery(mediaQuery: MediaQuery, callback: MediaQueryCallback) {
const handleMediaQuery = useCallback((event: MediaQueryListEvent) => {
if (event.media === mediaQuery) {
callback(event);
}
}, [mediaQuery, callback] );
useEffect(() => {
if (window?.matchMedia) {
const mediaQueryList = window.matchMedia(mediaQuery);
mediaQueryList.addEventListener('change', handleMediaQuery);
return () => {
mediaQueryList.removeEventListener('change', handleMediaQuery);
};
}
}, []);
}
/**
### Usage
function handlePrintMediaQuery(mediaQueryListEvent: MediaQueryListEvent) {
// Do something
}
useMediaQuery('print', handlePrintMediaQuery)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment