Created
October 30, 2020 07:40
-
-
Save will-t-harris/d04b701ec8ba5047dd3bf40c7bda0104 to your computer and use it in GitHub Desktop.
React useMediaQuery
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
/** Takes a media query and returns a boolean value for whether or not specified media query was hit. | |
* -- e.g. '(min-width: 567px)' | |
*/ | |
export const useMediaQuery = (query: string): boolean => { | |
const mediaMatch: MediaQueryList = window.matchMedia(query); | |
const [matches, setMatches] = useState<boolean>(mediaMatch.matches); | |
useEffect(() => { | |
const handler = e => setMatches(e.matches); | |
mediaMatch.addEventListener('change', handler); | |
return () => mediaMatch.removeEventListener('change', handler); | |
}); | |
return matches; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment