📱

モバイル判定

に公開2
import { useEffect, useState } from "react"

const MOBILE_BREAKPOINT = 768

export function useIsMobile() {
  const [isMobile, setIsMobile] = useState<boolean | undefined>(undefined)

  useEffect(() => {
    const isSp = window.innerWidth < MOBILE_BREAKPOINT
    const mq = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
    const onChange = () => {
      setIsMobile(isSp)  2️⃣ 画面サイズが変わった時に実行される
    }
    mq.addEventListener("change", onChange)
    setIsMobile(isSp)    1️⃣ 初回レンダー直後に現在のサイズを反映
    
    return () => mq.removeEventListener("change", onChange)
  }, [])

  return !!isMobile
}

Discussion