JAVASCRIPT
React Responsiveness with useMediaQuery Hook
Implement a custom React hook to detect CSS media query matches, allowing components to adapt their behavior or rendering based on real-time screen size changes.
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(() => {
if (typeof window !== 'undefined') {
return window.matchMedia(query).matches;
}
return false; // Default for SSR or environments without window
});
useEffect(() => {
if (typeof window === 'undefined') return;
const mediaQueryList = window.matchMedia(query);
const listener = (event) => setMatches(event.matches);
// Initial check (already done by useState, but good for consistency)
setMatches(mediaQueryList.matches);
mediaQueryList.addEventListener('change', listener);
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}, [query]);
return matches;
}
// How to use it:
// function MyResponsiveComponent() {
// const isLargeScreen = useMediaQuery('(min-width: 1024px)');
// return (
// <div>
// {isLargeScreen ? (
// <h1>This is a large screen layout!</h1>
// ) : (
// <h2>This is a small screen layout.</h2>
// )}
// </div>
// );
// }
How it works: The `useMediaQuery` hook enables dynamic, JavaScript-driven responsive design within React components. It takes a CSS media query string and returns a boolean indicating whether the query currently matches the viewport. Internally, it uses `window.matchMedia` to create a `MediaQueryList` object and subscribes to its `change` events via `addEventListener`. This ensures that the component re-renders and adapts whenever the media query's match status changes (e.g., when the browser window is resized).