Uqudo UIregistry

useIsMobile

Hook that reports whether the viewport is below the 768px mobile breakpoint.

Desktop viewport

Resize the window to see the value change.

Installation

npx shadcn@latest add @uqudo/use-mobile

Usage

import { useIsMobile } from "@/hooks/use-mobile"
"use client"

export function ResponsiveMenu() {
  const isMobile = useIsMobile()

  return isMobile ? <Sheet>...</Sheet> : <DropdownMenu>...</DropdownMenu>
}

useIsMobile is a client hook. It subscribes to a matchMedia query for (max-width: 767px) and re-renders when the viewport crosses the 768px breakpoint.

The hook returns false during server rendering and hydration, then updates to the real value on the client. Use it to switch behaviour (which component to open, whether to enable a gesture), not for layout that must be correct at first paint: for that, use responsive Tailwind classes.

API Reference

useIsMobile

Takes no arguments.

Prop

Type

Implementation

hooks/use-mobile.ts
import * as React from "react"

const MOBILE_BREAKPOINT = 768

function subscribe(onChange: () => void) {
  const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
  mql.addEventListener("change", onChange)
  return () => mql.removeEventListener("change", onChange)
}

function getSnapshot() {
  return window.innerWidth < MOBILE_BREAKPOINT
}

function getServerSnapshot() {
  return false
}

export function useIsMobile() {
  return React.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
}

On this page