Skip to content

Instantly share code, notes, and snippets.

@mjackson
Created July 25, 2019 01:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjackson/18fdec91e87c794ffbc8878df66afd0b to your computer and use it in GitHub Desktop.
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
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