Skip to main content

useMediaQuery

The useMediaQuery hook allows you to programmatically detect whether a CSS media query matches the current viewport, with full support for server-side rendering. Note: This hook is currently unstable and its API may change in future versions.

Import

Usage

Basic usage to detect viewport width:

Media query syntax

You can use any valid CSS media query. The @media prefix is optional:

Server-side rendering

Provide a default match value for server-side rendering:

API Reference

Parameters

query

  • Type: string
  • Required
The media query string to match. The @media prefix is optional and will be stripped if provided.

options

  • Type: UseMediaQueryOptions
  • Required
Configuration options for the hook.

Options

defaultMatches

  • Type: boolean
  • Default: false
  • Optional
As window.matchMedia() is unavailable on the server, the hook returns this value during the first mount. This enables hydration without mismatches.

matchMedia

  • Type: typeof window.matchMedia
  • Optional
Custom implementation of matchMedia. Useful for handling iframe content windows. Example:

noSsr

  • Type: boolean
  • Default: false
  • Optional
Skips the double-pass rendering for server-side hydration. Set to true if you use the returned value only client-side, which improves performance by avoiding the extra render.

ssrMatchMedia

  • Type: (query: string) => { matches: boolean }
  • Optional
Custom implementation of matchMedia for server-side rendering. Allows you to determine matches on the server based on request headers or other server-side context. Example:

Return Value

Returns true if the media query matches the current environment, false otherwise.

Use Cases

Responsive components

Create components that adapt to different screen sizes:

Theme detection

Detect user’s color scheme preference:

Conditional feature loading

Load features based on device capabilities:

Multiple breakpoints

Track multiple breakpoints simultaneously:

Server-side device detection

Use request headers to determine matches on the server: