useMediaMatch
Subscribes to a CSS media query with a deterministic server-rendered fallback.
About
useMediaMatch returns whether window.matchMedia() currently matches a CSS media query. It uses useSyncExternalStore so query changes, subscription cleanup, server snapshots, and hydration follow React's external-store model.
Example
import { useMediaMatch } from "rooks";
export default function ResponsiveMessage() {
const hasWideViewport = useMediaMatch("(min-width: 48rem)");
return (
<p style={{ padding: 12, border: "1px solid" }}>
{hasWideViewport ? "Wide layout is active" : "Compact layout is active"}
</p>
);
}Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
query | string | required | Any query accepted by window.matchMedia(). |
defaultServerRenderedValue | boolean | false | Snapshot returned on the server and during hydration. |
Return value
Returns a single boolean: the server fallback when no client store is available, otherwise the current MediaQueryList.matches value.
Behavior and lifecycle
The hook creates a MediaQueryList for the query, subscribes to its change event, and removes that listener when the query changes or the component unmounts. A query change creates and reads a new list. The server fallback does not override the value in a browser.
Choose a server value that produces safe, deterministic markup. React hydrates from that snapshot and then reconciles to the real client match; rendering structurally different trees for the two values can still produce a visible layout shift.
Compatibility and accessibility
The hook requires window.matchMedia and the modern MediaQueryList.addEventListener API. It does not contain a legacy addListener fallback. Server rendering itself does not access window.
Media queries can support responsive presentation, but DOM order and meaning should remain coherent at every result. For user preferences, prefer focused hooks such as usePrefersReducedMotion and preserve the corresponding accessible behavior in CSS as well. See SSR and browser APIs.
Related
- usePreferredColorScheme tracks light and dark preferences with a legacy-listener fallback.
- usePrefersReducedMotion targets the reduced-motion preference.
- useWindowSize returns viewport dimensions rather than a query result.