Created
December 1, 2021 20:47
-
-
Save djanowski/2fd49dcf4c0acc5ff7bada44ea26b935 to your computer and use it in GitHub Desktop.
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
function useMatchMedia(query) { | |
const mediaQuery = useMemo(() => window.matchMedia(query), [ query ]); | |
const [ matches, setMatches ] = useState(mediaQuery.matches); | |
useEffect(() => { | |
function onChange({ matches: newMatches }) { | |
setMatches(newMatches); | |
} | |
if (mediaQuery.addEventListener) | |
mediaQuery.addEventListener('change', onChange); | |
else | |
mediaQuery.addListener(onChange); | |
return () => { | |
if (mediaQuery.removeEventListener) | |
mediaQuery.removeEventListener('change', onChange); | |
else | |
mediaQuery.removeListener(onChange); | |
}; | |
}, [ mediaQuery ]); | |
return matches; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment