Last active
September 11, 2019 23:41
-
-
Save nathansh/5ad9891cbdabf3b1deb4112e03de1a7d to your computer and use it in GitHub Desktop.
React Hook 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
// const small = useMediaQuery('900px'); | |
// return ( <h3>{small ? 'Small' : 'Large'}</h3> ); | |
const useMediaQuery = (size, bound = 'max') => { | |
const query = `(${bound}-width: ${size})`; | |
const [matches, setMatches] = useState(window.matchMedia(query).matches); | |
useEffect(() => { | |
const mediaQuery = window.matchMedia(query); | |
const updateMatches = (newValue) => { | |
if (newValue.matches !== matches) { | |
setMatches(newValue.matches); | |
} | |
} | |
const listener = () => updateMatches(mediaQuery); | |
updateMatches(mediaQuery); | |
mediaQuery.addListener(listener); | |
return () => { | |
mediaQuery.removeListener(listener); | |
}; | |
}, [matches, query]); | |
return matches; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment