Utilitieshook
useIsMobile
Tracks whether the viewport is below the mobile breakpoint.
This viewport is desktopResize the window to see it change.
Installation
npx shadcn@latest add @particular/use-mobileSource
import * as React from "react"
const MOBILE_BREAKPOINT = 768
const QUERY = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`
function subscribe(onChange: () => void) {
const mql = window.matchMedia(QUERY)
mql.addEventListener("change", onChange)
return () => mql.removeEventListener("change", onChange)
}
export function useIsMobile() {
return React.useSyncExternalStore(
subscribe,
() => window.matchMedia(QUERY).matches,
() => false
)
}