Created
July 6, 2021 15:49
-
-
Save bfodeke/aad4d8e0651e6a36130b73bb5e7c9b87 to your computer and use it in GitHub Desktop.
React mediaquery hook
This file contains hidden or 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 { useState, useEffect } from 'react'; | |
export function useMediaQuery(query) { | |
const [matches, setMatches] = useState(false); | |
useEffect(() => { | |
const media: MediaQueryList = window.matchMedia(query); | |
if (media.matches !== matches) { | |
setMatches(media.matches); | |
} | |
const listener = () => { | |
setMatches(media.matches); | |
}; | |
media.addEventListener('change', listener); | |
return () => media.removeEventListener('change', listener); | |
}, [matches, query]); | |
return matches; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage