Function: useMediaQuery()
useMediaQuery(
query,options?):boolean
Defined in: use-media-query.ts:64
Subscribes to a CSS media query and returns whether it currently matches.
- Hydration-safe: built on
useSyncExternalStore, so the server and the first client render both usedefaultValue, then React re-renders with the real value if it differs. - Live: re-renders only when the match state flips, not on every viewport change.
- Dynamic queries: changing
queryre-subscribes and re-reads the match. - Graceful fallback: returns
defaultValuewhenmatchMediais unavailable (SSR, some test environments).
Any media feature works, not just widths: prefers-color-scheme,
prefers-reduced-motion, orientation, hover, print and so on.
Parameters
query
string
A CSS media query, for example "(min-width: 768px)".
options?
Optional defaultValue and onChange callback.
Returns
boolean
true when the query currently matches.
Examples
const isDesktop = useMediaQuery("(min-width: 1024px)");
// Reflect the user's OS setting, assuming "no match" until hydrated
const prefersDark = useMediaQuery("(prefers-color-scheme: dark)", {
onChange: (dark) => console.log(dark ? "dark" : "light"),
});
// Compose your own helpers on top
const useBreakpoint = (px: number) => useMediaQuery(`(min-width: ${px}px)`);
const usePrefersReducedMotion = () =>
useMediaQuery("(prefers-reduced-motion: reduce)");
For a live, editable example, see the useMediaQuery docs page.