JAVASCRIPT
Reacting to CSS Media Queries with useMediaQuery
Develop a `useMediaQuery` React hook to dynamically detect matching CSS media queries in JavaScript, enabling responsive component rendering.
function useMediaQuery(query) {
const [matches, setMatches] = React.useState(false);
React.useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => setMatches(media.matches);
media.addEventListener('change', listener);
return () => media.removeEventListener('change', listener);
}, [matches, query]); // Re-run if query changes
return matches;
}
// Example usage:
function ResponsiveComponent() {
const isLargeScreen = useMediaQuery('(min-width: 1024px)');
return (
React.createElement("div", null,
React.createElement("h1", null, "Screen Size: ", isLargeScreen ? 'Large' : 'Small'),
isLargeScreen ? (
React.createElement("p", null, "This content is visible on large screens.")
) : (
React.createElement("p", null, "This content is visible on small screens.")
)
)
);
}
How it works: The `useMediaQuery` hook allows React components to react to CSS media queries dynamically from JavaScript. It utilizes the `window.matchMedia` API to evaluate a given media query string and subscribes to changes using `addEventListener('change')`. The hook returns a boolean state indicating whether the media query currently matches. This enables conditional rendering, styling, or logic adjustments in React components based on screen size, orientation, or other media features, providing a powerful way to build truly responsive UIs.