JAVASCRIPT
Adapt React Components with useMediaQuery for Responsive Design
Create a React useMediaQuery hook to dynamically render UI based on CSS media queries, enabling truly responsive components that react to screen size changes.
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const mediaQueryList = window.matchMedia(query);
const listener = (event) => setMatches(event.matches);
// Set initial state
setMatches(mediaQueryList.matches);
// Listen for changes
mediaQueryList.addEventListener('change', listener);
// Cleanup
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}, [query]);
return matches;
}
// How to use it:
// function ResponsiveComponent() {
// const isLargeScreen = useMediaQuery('(min-width: 1024px)');
// return (
// <div>
// {isLargeScreen ? (
// <h1>You are on a large screen!</h1>
// ) : (
// <h2>You are on a smaller screen.</h2>
// )}
// </div>
// );
// }
How it works: The `useMediaQuery` hook accepts a CSS media query string. It leverages `window.matchMedia` to determine if the query currently matches and updates a `matches` state accordingly. It also adds and removes an event listener for the `change` event on the `MediaQueryList` object, ensuring the state is updated whenever the media query's matching status changes, making components responsive.