JAVASCRIPT

React to CSS Media Queries in Components

A custom React hook to dynamically detect if a CSS media query matches, enabling responsive component rendering based on screen size or other device characteristics.

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

    // Initial check
    setMatches(mediaQueryList.matches);

    // Listen for changes
    mediaQueryList.addEventListener('change', listener);

    return () => {
      mediaQueryList.removeEventListener('change', listener);
    };
  }, [query]);

  return matches;
}

// Example Usage:
// import React from 'react';
// function ResponsiveText() {
//   const isLargeScreen = useMediaQuery('(min-width: 768px)');

//   return (
//     <div>
//       <p>
//         {isLargeScreen
//           ? 'You are on a large screen.'
//           : 'You are on a small screen.'}
//       </p>
//     </div>
//   );
// }
How it works: This hook provides a way to detect whether a given CSS media query currently matches the user's environment. It leverages the browser's `window.matchMedia` API, updating its internal state whenever the media query's status changes. This is incredibly useful for rendering different UI elements or applying conditional logic based on screen size, dark mode preference, or other media features directly within your React components.

Need help integrating this into your project?

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

Hire DigitalCodeLabs