Last active
June 14, 2022 17:17
-
-
Save richcsmith/d8a48635636ba735467b44bf51be43f3 to your computer and use it in GitHub Desktop.
React/TypeScript Media Query Hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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