useMediaQuery — Responsive Breakpoint Hook
Subscribe to CSS media query changes and get a boolean flag for responsive rendering logic in React.
import { useState, useEffect } from 'react';
export function useMediaQuery(query: string): boolean {
const [matches, setMatches] = useState(() => {
if (typeof window === 'undefined') return false;
return window.matchMedia(query).matches;
});
useEffect(() => {
const mql = window.matchMedia(query);
const handler = (e: MediaQueryListEvent) => setMatches(e.matches);
mql.addEventListener('change', handler);
setMatches(mql.matches);
return () => mql.removeEventListener('change', handler);
}, [query]);
return matches;
}
// Usage:
// const isMobile = useMediaQuery('(max-width: 768px)');
// const prefersDark = useMediaQuery('(prefers-color-scheme: dark)');Use Cases
- Responsive layouts
- Conditional component rendering
- Dark mode detection
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
useWindowSize Hook
Track browser window dimensions with debounced resize handling for responsive component logic.
useFetch — Generic Data Fetching Hook
Custom React hook for data fetching with loading, error, and refetch states using the Fetch API.
useDebounce — Debounced Value Hook
Debounce any rapidly-changing value with a configurable delay. Useful for search inputs and resize handlers.
useLocalStorage — Persistent State Hook
Sync React state with localStorage including SSR safety, JSON serialization, and cross-tab updates.