JAVASCRIPT
React Hook for Responding to CSS Media Queries
Dynamically adjust your React UI based on CSS media queries using the `useMediaQuery` hook, enabling responsive designs directly within your components.
import { useState, useEffect } from 'react';
function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const mediaQuery = window.matchMedia(query);
setMatches(mediaQuery.matches);
const handler = (event) => setMatches(event.matches);
mediaQuery.addEventListener('change', handler);
return () => mediaQuery.removeEventListener('change', handler);
}, [query]);
return matches;
}
How it works: This hook allows your React components to react to CSS media query changes programmatically. It takes a media query string (e.g., `'(min-width: 768px)'`) and returns `true` if the query matches, and `false` otherwise. It automatically updates its value when the media query's status changes, making it excellent for building responsive user interfaces directly within component logic.