JAVASCRIPT

Respond to CSS Media Queries with `useMediaQuery` React Hook

Implement a `useMediaQuery` hook in React to detect if a given CSS media query matches, enabling dynamic component rendering based on screen size or device features.

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;
}

// Example Usage:
// function ResponsiveComponent() {
//   const isLargeScreen = useMediaQuery('(min-width: 1024px)');
//   const isDarkMode = useMediaQuery('(prefers-color-scheme: dark)');

//   return (
//     <div>
//       {isLargeScreen ? (
//         <h1>Welcome to the large screen layout!</h1>
//       ) : (
//         <h2>Viewing on a smaller screen.</h2>
//       )}
//       <p>Dark mode preference: {isDarkMode ? 'Yes' : 'No'}</p>
//     </div>
//   );
// }
How it works: The `useMediaQuery` hook provides a way to subscribe to changes in CSS media queries within React components. It takes a media query string (e.g., `(min-width: 768px)`) and returns a boolean indicating whether the query currently matches. This allows components to dynamically adjust their rendering or behavior based on responsive design conditions.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs