Hooks
useMediaQuery
BetaSince 0.1.0
Whether the page matches a CSS media query, such as reduced motion, updated as it changes.
import { useMediaQuery } from "@anantya/uix";Overview
useMediaQuery tells you whether the page matches a CSS media query, such as (prefers-reduced-motion: reduce) or (min-width: 64rem), and updates when that changes. Use it when what your code does depends on the device, such as whether a preview shows on the page or in a Dialog, or whether to scroll smoothly.
To change only how something looks, use Tailwind's variants, such as md: or motion-safe:, instead. They are right from the first paint.
Signature
function useMediaQuery(query: string, options?: UseMediaQueryOptions): boolean;
interface UseMediaQueryOptions {
defaultValue?: boolean;
}Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
query | string | - | A CSS media query, such as "(min-width: 64rem)". |
options.defaultValue | boolean | false | The result on the server, during hydration and where the browser can't tell. |
Returns
Whether the page matches query. On the server and during hydration it is defaultValue, so the server and client HTML match, and the real result follows once hydration is done. A component first rendered after hydration gets the real result straight away.
Example
On a screen at least 48rem wide, the invoice shows on the page. On a narrower one, Preview invoice opens it in a full-screen Dialog. Narrow the window to see it switch.
Code
"use client";
import {
Dialog,
DialogBody,
DialogContent,
DialogFooter,
DialogTitle,
DialogTrigger,
useMediaQuery,
} from "@anantya/uix";
function Preview() {
return <p className="text-sm">Mehta Textiles, ₹48,500, due 30 Nov 2026</p>;
}
export default function InvoicePreview() {
const wide = useMediaQuery("(min-width: 48rem)");
if (wide) {
return (
<section aria-label="Invoice INV-2026-0142" className="rounded-xl border border-border p-4">
<Preview />
</section>
);
}
return (
<Dialog>
<DialogTrigger variant="secondary">Preview invoice</DialogTrigger>
<DialogContent size="full">
<DialogTitle>Invoice INV-2026-0142</DialogTitle>
<DialogBody>
<Preview />
</DialogBody>
<DialogFooter cancel="Done" />
</DialogContent>
</Dialog>
);
}Notes
- Until hydration is done it returns
defaultValue, so pick the result most readers get, such asfalsefor(min-width: 48rem)in an app used mostly on phones - Use
remin width queries, as Tailwind's breakpoints do, so they follow the reader's text size - A query the browser doesn't understand never matches
Changelog
Every change to useMediaQuery since 0.1.0 is in the release notes.