useMediaQuery
Subscribe to a CSS media query and re-render when it starts or stops matching.
Installation
npx shadcn@latest add @redpanda/use-media-querypnpm dlx shadcn@latest add @redpanda/use-media-queryyarn dlx shadcn@latest add @redpanda/use-media-querybunx shadcn@latest add @redpanda/use-media-querynubx shadcn@latest add @redpanda/use-media-queryaube dlx shadcn@latest add @redpanda/use-media-queryuseMediaQuery returns a boolean that tracks whether a CSS media query currently matches, updating on change. Use it for responsive behavior that can’t be expressed in CSS alone — swapping a Dialog for a Drawer, collapsing a layout, or toggling interaction patterns by viewport.
Usage
import { useMediaQuery } from "@/hooks/use-media-query";
function Responsive() {
const isDesktop = useMediaQuery("(min-width: 768px)");
return isDesktop ? <DesktopNav /> : <MobileNav />;
}
API
useMediaQuery(query)
| Parameter | Type | Description |
|---|---|---|
query |
string |
A CSS media query string, e.g. (min-width: 768px). |
Returns boolean — whether the query currently matches.
Related
For the common “is this a phone-sized viewport” check, prefer useIsMobile, which wraps this with the design system’s mobile breakpoint.