Created
July 1, 2020 20:15
-
-
Save cvan/468b6ba4e070288106024735bdce2e37 to your computer and use it in GitHub Desktop.
useMedia - React hook for `window.matchMedia` for matching media-query
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 useMedia(mediaQuery) { | |
const match = () => { | |
if (!window.matchMedia) { | |
return false; | |
} | |
return window.matchMedia(mediaQuery).matches; | |
}; | |
const [value, set] = useState(match); | |
useEffect(() => { | |
// Update state on window `resize` event. | |
// Usage of `match` function defined outside of `useEffect` | |
// ensures that it has current values of arguments. | |
const handler = () => set(match); | |
window.addEventListener('resize', handler); | |
// Remove event listener on cleanup. | |
return () => window.removeEventListener('resize', handler); | |
}); | |
return value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment