JAVASCRIPT
Respond to CSS Media Queries with useMediaQuery Hook
Create a React hook to dynamically detect and respond to CSS media queries within your component logic, enabling responsive behavior directly in JavaScript.
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
if (typeof window !== 'undefined' && window.matchMedia) {
const mediaQueryList = window.matchMedia(query);
const listener = (event) => setMatches(event.matches);
// Set initial state
setMatches(mediaQueryList.matches);
// Listen for changes
mediaQueryList.addEventListener('change', listener);
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}
return undefined; // Or handle SSR more explicitly
}, [query]);
return matches;
}
// Example usage:
// function ResponsiveComponent() {
// const isLargeScreen = useMediaQuery('(min-width: 1024px)');
// const isMobile = useMediaQuery('(max-width: 768px)');
// return (
// <div>
// <p>{isLargeScreen ? 'You are on a large screen!' : 'Screen is not large.'}</p>
// <p>{isMobile ? 'Viewing on a mobile device.' : 'Not on a mobile device.'}</p>
// {isMobile && <button>Mobile-specific button</button>}
// </div>
// );
// }
How it works: The `useMediaQuery` hook allows React components to react dynamically to CSS media queries. It uses the `window.matchMedia` API to evaluate a given media query string and provides a boolean state indicating whether the query currently matches. This is invaluable for implementing JavaScript-driven responsive layouts, conditional rendering, or executing specific logic based on screen size or other media features, offering fine-grained control beyond what pure CSS can provide.