useMediaQuery
TheuseMediaQuery 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
@media prefix is optional and will be stripped if provided.
options
- Type:
UseMediaQueryOptions - Required
Options
defaultMatches
- Type:
boolean - Default:
false - Optional
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
matchMedia. Useful for handling iframe content windows.
Example:
noSsr
- Type:
boolean - Default:
false - Optional
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
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
Returnstrue if the media query matches the current environment, false otherwise.