use-mobile.ts 585 B

123456789101112131415161718192021
  1. import * as React from "react";
  2. const MOBILE_BREAKPOINT = 768;
  3. export function useIsMobile() {
  4. const [isMobile, setIsMobile] = React.useState<boolean | undefined>(
  5. undefined,
  6. );
  7. React.useEffect(() => {
  8. const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
  9. const onChange = () => {
  10. setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
  11. };
  12. mql.addEventListener("change", onChange);
  13. setIsMobile(window.innerWidth < MOBILE_BREAKPOINT);
  14. return () => mql.removeEventListener("change", onChange);
  15. }, []);
  16. return !!isMobile;
  17. }