use-mobile.tsx 565 B

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