JAVASCRIPT
Responding to Media Queries with useMediaQuery
Build a custom React hook `useMediaQuery` to programmatically detect and react to CSS media query changes, enabling dynamic responsive UI adjustments in your components.
import { useState, useEffect } from 'react';
const useMediaQuery = (query) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
// Check if window is defined (for SSR compatibility)
if (typeof window === 'undefined' || !window.matchMedia) {
return;
}
const mediaQueryList = window.matchMedia(query);
const listener = (event) => setMatches(event.matches);
// Initial check
setMatches(mediaQueryList.matches);
// Add listener for changes
mediaQueryList.addEventListener('change', listener);
// Cleanup
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}, [query]); // Re-run if the media query string changes
return matches;
};
export default useMediaQuery;
// Example Usage:
// function ResponsiveText() {
// const isLargeScreen = useMediaQuery('(min-width: 1024px)');
// const isTablet = useMediaQuery('(min-width: 768px) and (max-width: 1023px)');
// const isMobile = useMediaQuery('(max-width: 767px)');
//
// return (
// <div>
// {isLargeScreen && <p>You are on a large screen!</p>}
// {isTablet && <p>You are on a tablet!</p>}
// {isMobile && <p>You are on a mobile device!</p>}
// <p>Current screen width is {window.innerWidth}px.</p>
// </div>
// );
// }
How it works: The `useMediaQuery` hook allows React components to respond dynamically to CSS media query changes. It takes a media query string (e.g., `'(min-width: 768px)'`) and returns a boolean indicating whether the query currently matches. Internally, it uses `window.matchMedia` and its `addEventListener` method to subscribe to changes, updating the component's state whenever the media query's matching status changes. This is invaluable for implementing responsive layouts and conditionally rendering content based on screen size.