useMediaQuery

A hook that subscribes to a CSS media query and returns whether it matches, with Tailwind-style breakpoint shorthand ("md", "max-md") instead of hand-written CSS query strings. Built on useSyncExternalStore for SSR safety and concurrent mode compatibility. Powers Responsive Dialog, Responsive Menu, and Responsive Alert Dialog.

Last updated August 12, 2026

CreditsUnchangedPublished

Copied from coss ui.

Overview

Installation

$ npx shadcn@latest add https://ui.persian-labs.ir/r/use-media-query.json

Usage

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

import { useMediaQuery } from "@/hooks/use-media-query"
 
// Min-width (breakpoint and above) — like md:
const isDesktop = useMediaQuery("md")
 
// Max-width (below breakpoint) — like max-md:
const isMobile = useMediaQuery("max-md")
 
// Range (between two breakpoints) — like md:max-lg:
const isTablet = useMediaQuery("md:max-lg")

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

// Touch device detection
const isTouch = useMediaQuery({ pointer: "coarse" })
 
// Breakpoint + pointer combined
const isMobileTouch = useMediaQuery({ max: "md", pointer: "coarse" })
 
// Custom pixel values
const isNarrow = useMediaQuery({ max: 600 })

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

const prefersDark = useMediaQuery("(prefers-color-scheme: dark)")
const prefersReducedMotion = useMediaQuery("(prefers-reduced-motion: reduce)")

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

function Layout() {
  const isDesktop = useMediaQuery("lg")
 
  return isDesktop ? <DesktopNav /> : <MobileNav />
}

The hook includes a static breakpoint map that must match your Tailwind config. If you override breakpoints in your Tailwind CSS @theme, update the BREAKPOINTS constant in the hook to match.

NameValue
sm640px
md800px
lg1024px
xl1280px
2xl1536px
3xl1600px
4xl2000px

Examples

Breakpoints

Min-width — resize the viewport to see values update live.

Ranges

Matches only between two breakpoints.

Device & preferences

Pointer type and raw preference queries.

RTL

API Reference

useMediaQuery(query)

MediaQueryInput