9.4k

useMediaQuery

Reactive media query hook with Tailwind-like syntax.

A React hook that subscribes to a CSS media query and returns whether it matches. Built on useSyncExternalStore for SSR safety and concurrent mode compatibility.

Installation

Usage

Breakpoint shorthand

Use Tailwind variant syntax to match breakpoints. TypeScript provides full autocomplete.

Object API

Use the object form when you need pointer detection or custom pixel values.

Raw media query

Pass any valid CSS media query string as an escape hatch.

Conditional rendering

The primary use case — mount one component instead of another based on viewport.

Breakpoints

The hook includes a static breakpoint map that must match your Tailwind config. Default values:

If you override breakpoints in your Tailwind CSS @theme, update the BREAKPOINTS constant in the hook to match.

API

String queries

Object queries

Return value

Returns booleantrue when the media query matches, false otherwise. Returns false during SSR.

Examples

Resize the viewport to see values update in real time.

Min-width (breakpoint and above)

  • useMediaQuery("sm")
    ≥ 640pxfalse
  • useMediaQuery("md")
    ≥ 800pxfalse
  • useMediaQuery("lg")
    ≥ 1024pxfalse
  • useMediaQuery("xl")
    ≥ 1280pxfalse
  • useMediaQuery("2xl")
    ≥ 1536pxfalse

Max-width (below breakpoint)

  • useMediaQuery("max-sm")
    < 640pxfalse
  • useMediaQuery("max-md")
    < 800pxfalse
  • useMediaQuery("max-lg")
    < 1024pxfalse

Ranges

  • useMediaQuery("sm:max-md")
    640 - 799pxfalse
  • useMediaQuery("md:max-lg")
    800 - 1023pxfalse
  • useMediaQuery("lg:max-xl")
    1024 - 1279pxfalse

Device & preferences

  • useMediaQuery({ pointer: "coarse" })
    touchfalse
  • useMediaQuery({ pointer: "fine" })
    mousefalse
  • useMediaQuery("(prefers-color-scheme: dark)")
    false
  • useMediaQuery("(prefers-reduced-motion: reduce)")
    false

Convenience export

The hook also exports useIsMobile for backward compatibility with shadcn's use-mobile pattern:

coss.com ui

Built by and for the team of Cal.com, Inc. — the leading commercial open source company (“coss”).