JAVASCRIPT
React useMediaQuery Hook for Responsive UI Logic
Build a `useMediaQuery` React hook to integrate CSS media queries directly into your component logic, enabling dynamic, responsive UI behaviors.
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
if (typeof window !== 'undefined' && window.matchMedia) {
const mediaQueryList = window.matchMedia(query);
setMatches(mediaQueryList.matches);
const listener = (event) => setMatches(event.matches);
mediaQueryList.addEventListener('change', listener);
return () => {
mediaQueryList.removeEventListener('change', listener);
};
}
return undefined;
}, [query]);
return matches;
}
How it works: The `useMediaQuery` hook allows React components to respond to CSS media queries dynamically. It initializes state with the current match status of the given `query` using `window.matchMedia`. A `useEffect` then sets up a listener for changes to the media query and updates the state accordingly. This enables rendering different UI elements or applying conditional logic based on screen size, orientation, or other media features directly within your React components.