JAVASCRIPT
React to CSS Media Queries
A custom React hook that allows components to react dynamically to CSS media queries, enabling responsive UI changes directly within your React logic.
import { useState, useEffect } from 'react';
const useMediaQuery = (query) => {
const [matches, setMatches] = useState(false);
useEffect(() => {
if (typeof window === 'undefined' || !window.matchMedia) {
return; // Not available in SSR or older browsers
}
const mediaQueryList = window.matchMedia(query);
const listener = (event) => {
setMatches(event.matches);
};
mediaQueryList.addEventListener('change', listener);
setMatches(mediaQueryList.matches); // Set initial value
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}, [query]);
return matches;
};
export default useMediaQuery;
How it works: This hook takes a CSS media query string (e.g., `(min-width: 768px)`). It uses `window.matchMedia` to evaluate the query and set the initial `matches` state. A `change` event listener is then added to the `MediaQueryList` object, updating the `matches` state whenever the media query status changes (e.g., resizing the browser window past a breakpoint). The listener is cleaned up on unmount to prevent memory leaks.