useMediaQuery
TheuseMediaQuery hook allows you to reactively track CSS media query matches, enabling responsive behavior in your React components.
Import
Signature
Parameters
A valid CSS media query string to match against.Examples:
"(min-width: 768px)""(max-width: 1024px)""(prefers-color-scheme: dark)"
Return Value
Returns
true if the media query currently matches, false otherwise. Updates reactively when the match status changes.Usage
Basic Media Query
Tablet Detection
Dark Mode Detection
Responsive Navigation
useIsMobile Helper
A convenience hook that returnstrue when the viewport is below tablet size (< 768px).
Signature
Usage
Conditional Rendering
Common Breakpoints
Here are standard breakpoints you can use withuseMediaQuery:
- Mobile:
(max-width: 767px) - Tablet:
(min-width: 768px)and(max-width: 1023px) - Desktop:
(min-width: 1024px) - Large Desktop:
(min-width: 1280px)
The hook automatically handles cleanup and updates when the query match changes. It uses the native
window.matchMedia API for optimal performance.Best Practices
- Use Semantic Breakpoints: Define breakpoints based on your content needs, not specific devices
- Prefer CSS When Possible: Use CSS media queries for styling; use this hook when you need conditional logic or component swapping
- Avoid Excessive Queries: Minimize the number of different media queries to reduce re-renders
- Consider SSR: This hook returns
falseduring server-side rendering sincewindowis not available