Today I Learned

A Hashrocket project

Ready to join Hashrocket? Find Openings here and apply today.

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)!

Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.