Created
July 25, 2019 01:05
-
-
Save mjackson/18fdec91e87c794ffbc8878df66afd0b to your computer and use it in GitHub Desktop.
A React hook for listening to the state of a CSS 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
import { useEffect, useState } from 'react'; | |
export default function useMediaQuery(query, defaultValue) { | |
const [matches, setMatches] = useState(defaultValue); | |
useEffect(() => { | |
const mql = window.matchMedia(query); | |
setMatches(mql.matches); | |
mql.onchange = event => { | |
setMatches(event.matches); | |
}; | |
return () => { | |
mql.onchange = null; | |
}; | |
}, [query]); | |
return matches; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment