JAVASCRIPT
React to CSS Media Queries in JavaScript with useMediaQuery Hook
Create a `useMediaQuery` React hook to dynamically respond to CSS media query changes directly within your JavaScript components, enabling responsive logic.
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
if (typeof window === 'undefined' || !window.matchMedia) {
return;
}
const mediaQueryList = window.matchMedia(query);
const listener = (event) => {
setMatches(event.matches);
};
// Initial check
setMatches(mediaQueryList.matches);
// Listen for changes
mediaQueryList.addEventListener('change', listener);
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}, [query]);
return matches;
}
// Example Usage:
// function ResponsiveComponent() {
// const isLargeScreen = useMediaQuery('(min-width: 1024px)');
// const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)');
// return (
// <div style={{
// backgroundColor: isDarkMode ? '#333' : '#fff',
// color: isDarkMode ? '#fff' : '#333',
// padding: isLargeScreen ? '20px' : '10px',
// fontSize: isLargeScreen ? '1.5em' : '1em'
// }}>
// <p>This content adapts to screen size and dark mode preference.</p>
// {isLargeScreen && <p>You are on a large screen!</p>}
// {isDarkMode && <p>Dark mode is active!</p>}
// </div>
// );
// }
How it works: The `useMediaQuery` hook allows your React components to dynamically react to CSS media queries in JavaScript. It takes a media query string (e.g., `'(min-width: 768px)'`) and returns a boolean value indicating whether the query currently matches. This hook utilizes `window.matchMedia` and its `addEventListener` to subscribe to changes in the media query status, updating the component's state accordingly. This is highly useful for implementing responsive logic directly within your component's rendering or behavior, rather than relying solely on CSS.