useMediaQuery
TheuseMediaQuery hook evaluates CSS media queries in React and returns a boolean indicating whether the query matches the current viewport. It automatically updates when the viewport changes.
Installation
Import
Usage
Parameters
string
required
A CSS media query string to evaluate (e.g.,
"(min-width: 768px)", "(prefers-color-scheme: dark)").Returns
boolean
A boolean value indicating whether the media query currently matches. Updates automatically when the viewport or media conditions change.
Type Definition
Examples
Breakpoint Detection
Dark Mode Detection
Responsive Grid Layout
Orientation Detection
Reduced Motion Preference
Hover Capability Detection
Print Styles
Multiple Breakpoints
Conditional Feature Loading
Common Media Queries
Breakpoints
User Preferences
Device Capabilities
Display
Common Patterns
Creating a Custom Hook
Combining Multiple Queries
Notes
- The hook uses
window.matchMedia()which is supported in all modern browsers - The media query listener is automatically added and cleaned up
- The hook returns
falseinitially during server-side rendering - The initial value is set synchronously to match the current viewport
- Event listeners are properly cleaned up when the component unmounts or query changes
- Complex media queries are fully supported (combining multiple conditions with
and,or,not) - For better performance with multiple queries, consider memoizing or creating custom hooks