useMediaQuery
Ease with media query
useMediaQuery wraps window.matchMedia() to reactively evaluate a CSS media query string. It returns a boolean indicating whether the document currently matches the query. The value updates automatically whenever the match state changes (e.g., when the window is resized or the system color scheme changes).
When to Use
- Rendering different layouts or components based on screen width breakpoints
- Detecting system preferences like dark mode, reduced motion, or high contrast
- Conditionally loading heavy components or assets only on large screens
Notes
- SSR-safe: Accepts a
defaultStateparameter (default:false) that is returned during server-side rendering whenwindow.matchMediais not available. - Any valid media query: Works with any CSS media query string, including
prefers-color-scheme,prefers-reduced-motion,orientation, and custom breakpoints. - Related hooks: Several specialized hooks are built on
useMediaQuery, includingusePreferredDark,usePreferredColorScheme,usePreferredContrast,useReducedMotion, anduseMobileLandscape.
Usage
Live Editor
function Demo() { const isWide = useMediaQuery("(min-width: 480px)"); return <div>Screen is wide: {isWide ? "Yes" : "No"}</div>; };
Result
API
useMediaQuery
Returns
boolean: whether comply with media inquiries
Arguments
| Argument | Description | Type | DefaultValue |
|---|---|---|---|
| query | media query string | string (Required) | - |
| defaultState | default value | boolean | undefined | - |