Skip to main content

Overview

The useIsMobile hook provides a reactive boolean value that indicates whether the current viewport width is below the mobile breakpoint (768px). It listens to window resize events and updates automatically.

Usage

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

function ResponsiveComponent() {
  const isMobile = useIsMobile()
  
  return (
    <div>
      {isMobile ? (
        <MobileView />
      ) : (
        <DesktopView />
      )}
    </div>
  )
}

Signature

function useIsMobile(): boolean

Return value

isMobile
boolean
Returns true if the viewport width is less than 768px, false otherwise. Initially returns false during server-side rendering or before the first client-side measurement.

Breakpoint

The hook uses a fixed breakpoint constant:
const MOBILE_BREAKPOINT = 768
Viewports with width < 768px are considered mobile.

Behavior

Initial state

The hook returns false initially (via !!undefined) to handle server-side rendering and prevent hydration mismatches.

Reactive updates

The hook:
  1. Creates a media query listener for (max-width: 767px)
  2. Updates the state when the viewport crosses the breakpoint
  3. Checks window.innerWidth directly for precise measurements
  4. Cleans up the event listener on unmount

Implementation details

const [isMobile, setIsMobile] = React.useState<boolean | undefined>(undefined)

React.useEffect(() => {
  const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
  const onChange = () => {
    setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
  }
  mql.addEventListener("change", onChange)
  setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
  return () => mql.removeEventListener("change", onChange)
}, [])

return !!isMobile
The hook uses both matchMedia for efficient change detection and window.innerWidth for accurate width measurement.

Common patterns

Conditional rendering

function Layout() {
  const isMobile = useIsMobile()
  
  return isMobile ? <MobileSidebar /> : <DesktopSidebar />
}

Conditional styling

function Card() {
  const isMobile = useIsMobile()
  
  return (
    <div className={isMobile ? "p-4" : "p-8"}>
      Content
    </div>
  )
}

Feature toggling

function Chat() {
  const isMobile = useIsMobile()
  
  const maxMessages = isMobile ? 50 : 200
  
  return <MessageList limit={maxMessages} />
}
This hook is client-side only and will always return false during SSR to prevent hydration errors.

Source

See the full implementation in hooks/use-mobile.ts:5

Build docs developers (and LLMs) love