Watch Media query changes using React hooks
I end up creating a React hook to watch a media query change. I am using window.matchMedia
to achieve that. Check this out:
const useWatchMedia = (media) => {
const [matches, setMatches] = useState();
useEffect(() => {
const watchedMedia = window.matchMedia(media);
const mediaListener = () => setMatches(watchedMedia.matches);
mediaListener();
watchedMedia.addListener(mediaListener);
return () => watchedMedia.removeListener(mediaListener);
}, [media]);
return matches;
};
React hooks are an excellent way to share this setup (and cleanup)!
Tweet