Skip to content
On this page
Browser & DOMClient Component

useMediaQuery

Overview

useMediaQuery exposes MediaQueryList.matches through useSyncExternalStore and shares one native subscription for equal queries in the same window.

Signature

ts
function useMediaQuery(
  query: string,
  options?: { readonly defaultMatches?: boolean; readonly onError?: (error: unknown) => void },
): boolean;

Parameters

query is a CSS media query. defaultMatches is the server and unsupported-browser fallback, defaulting to false. onError observes matchMedia and subscription failures.

Returns

Whether the query currently matches.

Behavior

Subscribers share a cached MediaQueryList; the native listener is removed when the last subscriber leaves. Legacy addListener is used only when modern methods are absent. If matchMedia throws, the Hook reports the failure and returns defaultMatches instead of breaking the render.

SSR / RSC

The server snapshot is defaultMatches ?? false. Choose it deliberately to reduce disruptive hydration changes, and call the Hook in a Client Component.

Example

Composition

Prefer CSS for presentation-only changes. Use this Hook when matching state changes behavior or rendered semantics.

Source

Read the implementation on GitHub.