Skip to content

Instantly share code, notes, and snippets.

@nathansh
Last active September 11, 2019 23:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathansh/5ad9891cbdabf3b1deb4112e03de1a7d to your computer and use it in GitHub Desktop.
Save nathansh/5ad9891cbdabf3b1deb4112e03de1a7d to your computer and use it in GitHub Desktop.
React Hook Media Query
// 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