JAVASCRIPT
Reactively Respond to CSS Media Queries with useMediaQuery Hook
Use the `useMediaQuery` hook to dynamically apply JavaScript logic based on CSS media queries, enabling responsive behavior directly within your React components.
import { useState, useEffect } from 'react';
const useMediaQuery = (query) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
if (typeof window === 'undefined' || !window.matchMedia) {
return;
}
const mediaQueryList = window.matchMedia(query);
const documentChangeHandler = () => {
setMatches(mediaQueryList.matches);
};
documentChangeHandler(); // Set initial state
mediaQueryList.addEventListener('change', documentChangeHandler);
return () => {
mediaQueryList.removeEventListener('change', documentChangeHandler);
};
}, [query]);
return matches;
};
export default useMediaQuery;
How it works: This `useMediaQuery` hook allows components to react to CSS media query changes. It leverages `window.matchMedia` and its `addEventListener` to keep track of whether the specified media query currently matches, updating the component's state accordingly. This is useful for conditional rendering or styling based on screen size, dark mode preference, or other device characteristics.