useMediaQuery
A hook that detects screen size changes and other media features to help build responsive interfaces.
useMediaQuery
The useMediaQuery
hook allows you to easily respond to CSS media queries in your React components. It’s essential for building responsive layouts, implementing device-specific features, and respecting user preferences like dark mode or reduced motion.
Installation
Install the useMediaQuery hook using:
File Structure
Parameters
Prop | Type | Default |
---|---|---|
query | string | Required |
Return Value
Prop | Type | Default |
---|---|---|
matches | boolean | - |
Examples
Responsive Layout
Build a responsive layout that adapts to different screen sizes:
Card 1
Card 2
Current view: Desktop
Resize your browser window to see the layout change
User Preference Detection
Detect and respond to user preferences such as dark mode, reduced motion, and more:
Feature Detection
Use media queries for feature detection to enhance progressive enhancement:
Common Media Queries
Here are some common media queries you might use with this hook:
Screen Sizes
Orientation
User Preferences
Display Features
Use Cases
- Responsive Layouts: Adapt layouts based on screen size
- Conditional Rendering: Show or hide elements based on screen size
- Adaptive UX: Modify user experience based on device capabilities
- Accessibility: Respect user preferences like reduced motion
- Dark Mode: Implement automatic dark mode based on system preference
- Device-Specific Features: Enable/disable features based on device type
- Performance Optimization: Load different assets based on screen size
Accessibility
This hook can significantly improve accessibility by allowing you to:
- Respond to
prefers-reduced-motion
for users with vestibular disorders - Adapt to
prefers-contrast
for users with visual impairments - Support
prefers-color-scheme
for users who need specific color modes - Optimize touch targets when
pointer: coarse
is detected - Provide keyboard-focused UI when
hover: none
is detected
Server-Side Rendering
This hook includes safeguards for server-side rendering (SSR) by checking if window
is defined before accessing browser APIs. When rendering on the server, it returns false
by default.
For proper hydration with Next.js or similar frameworks, you can use this pattern:
Best Practices
- Use semantic breakpoints that match your design system
- Limit the number of media queries to avoid performance issues
- Extract common screen size queries into reusable constants or custom hooks
- Consider throttling or debouncing the state updates for rapid changes (like window resizing)
- Use with CSS-in-JS libraries to share the same breakpoint definitions
- Prefer
min-width
media queries for mobile-first design - Test thoroughly on various devices and browsers