Skip to main content

useMediaQuery

A React hook for detecting media query matches using the browser’s window.matchMedia API with support for SSR.
This utility is currently unstable and may change in future releases.

Import

Hook Signature

Parameters

string
required
The media query string to match. The @media prefix is optional and will be automatically removed if present.Example: "(min-width: 768px)" or "@media (min-width: 768px)"
useMediaQuery.Options
required
Configuration options for the media query matching behavior.

Options

boolean | undefined
default:"false"
As window.matchMedia() is unavailable on the server, it returns a default matches during the first mount.
typeof window.matchMedia | undefined
You can provide your own implementation of matchMedia. This can be used for handling an iframe content window.
boolean | undefined
default:"false"
To perform the server-side hydration, the hook needs to render twice. A first time with defaultMatches, the value of the server, and a second time with the resolved value. This double pass rendering cycle comes with a drawback: it’s slower. You can set this option to true if you use the returned value only client-side.
((query: string) => { matches: boolean }) | undefined
You can provide your own implementation of matchMedia, it’s used when rendering server-side.

Return Value

Returns true if the media query matches, false otherwise.

Type Definitions

useMediaQuery.Options

Usage Examples

Basic Usage

SSR with Custom Matching

Client-Side Only

SSR Considerations

Since window.matchMedia() is not available on the server:
  1. Default behavior: Returns defaultMatches on first render
  2. With ssrMatchMedia: Uses custom server-side matching logic
  3. With noSsr: true: Skips server-side rendering and only evaluates client-side
The hook uses useSyncExternalStore internally to ensure proper hydration and reactivity to media query changes.

Browser Support

This hook relies on window.matchMedia which is supported in all modern browsers. For jsdom environments (like test runners), a defensive check ensures the hook doesn’t crash when matchMedia is unavailable.