JAVASCRIPT
Conditionally Render Based on CSS Media Queries with useMediaQuery
Discover how to build a custom useMediaQuery React hook, enabling your components to dynamically adapt their rendering based on CSS media query changes for responsive UIs.
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
if (typeof window === 'undefined' || !window.matchMedia) {
return; // Server-side rendering or unsupported browser
}
const mediaQueryList = window.matchMedia(query);
const listener = (event) => setMatches(event.matches);
setMatches(mediaQueryList.matches); // Set initial state
mediaQueryList.addEventListener('change', listener);
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}, [query]);
return matches;
}
// Example Usage:
// function MyResponsiveComponent() {
// const isLargeScreen = useMediaQuery('(min-width: 1024px)');
// return (
// <div>
// {isLargeScreen ? <p>Large Screen Content</p> : <p>Small Screen Content</p>}
// </div>
// );
// }
How it works: The `useMediaQuery` hook provides a way for React components to react 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. This is invaluable for building responsive user interfaces where component rendering, layout, or behavior needs to change based on screen size, orientation, or other media features.