JAVASCRIPT
React useMediaQuery Hook for Responsive Designs
Dynamically adapt your React components based on CSS media queries, enabling responsive layouts and conditional rendering with ease.
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const mediaQueryList = window.matchMedia(query);
const listener = (event) => setMatches(event.matches);
// Set initial state
setMatches(mediaQueryList.matches);
// Add listener for changes
mediaQueryList.addEventListener('change', listener);
// Clean up
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}, [query]);
return matches;
}
How it works: The `useMediaQuery` hook allows components to react to CSS media queries. It takes a media query string (e.g., `(min-width: 768px)`) and returns a boolean indicating whether the query currently matches. Internally, it uses `window.matchMedia` to check the initial state and then adds an event listener for `change` events, ensuring the component re-renders and stays synchronized with the media query status.