JAVASCRIPT
Respond to CSS Media Queries with `useMediaQuery`
Build a `useMediaQuery` React hook to programmatically detect if a CSS media query matches, allowing dynamic component rendering and styling based on screen size.
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const mediaQuery = window.matchMedia(query);
const handleChange = (event) => {
setMatches(event.matches);
};
// Set initial state
setMatches(mediaQuery.matches);
// Listen for changes
mediaQuery.addEventListener('change', handleChange);
return () => {
mediaQuery.removeEventListener('change', handleChange);
};
}, [query]);
return matches;
}
// Example Usage:
/*
function ResponsiveComponent() {
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>
)}
<p>Window width is {isLargeScreen ? '1024px or more' : 'less than 1024px'}.</p>
</div>
);
}
*/
How it works: The `useMediaQuery` hook allows components to react dynamically to CSS media queries. It takes a `query` string (e.g., `(min-width: 768px)`). Inside `useEffect`, it uses `window.matchMedia` to create a `MediaQueryList` object, setting the initial `matches` state. It then adds an event listener for `change` events on this `MediaQueryList`, updating the state whenever the media query's matching status changes. This hook provides a powerful way to implement responsive behavior directly in JavaScript.