useMediaQuery

Watch the result of a CSS media query with a React hook.

import { useEffect, useState } from "react";

export const useMediaQuery = (query: string): boolean => {
  const mediaQuery = window.matchMedia(query);

  const [value, setValue] = useState(mediaQuery.matches);
  useEffect(() => {
    const handler = () => {
      setValue(mediaQuery.matches);
    };

    mediaQuery.addListener(handler);
    return () => mediaQuery.removeListener(handler);
  }, []);

  return value;
};

Usage

const MyComponent = () => {
  const isSmall = useMediaQuery(`(max-width: 40em)`);

  return <div>{isSmall ? "Small device" : "large device"}</div>;
};
Last Updated February 16, 2021