JAVASCRIPT

useMediaQuery for responsive component rendering

A useful React hook that allows components to react to CSS media queries, enabling dynamic rendering based on viewport size or 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);

      // Set initial match state
      setMatches(mediaQueryList.matches);

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

      // Cleanup listener on unmount
      return () => mediaQueryList.removeEventListener('change', listener);
    }, [query]); // Re-run if the query string changes

    return matches;
  }

  // Example Usage:
  // function ResponsiveText() {
  //   const isLargeScreen = useMediaQuery('(min-width: 1024px)');
  //   const isMobile = useMediaQuery('(max-width: 767px)');

  //   return (
  //     <div>
  //       {isLargeScreen && <p>This text is visible on large screens.</p>}
  //       {isMobile && <p>This text is visible on mobile devices.</p>}
  //       {!isLargeScreen && !isMobile && <p>This text is visible on medium screens.</p>}
  //     </div>
  //   );
  // }
How it works: The `useMediaQuery` hook enables React components to respond dynamically 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. Using `window.matchMedia` and listening for `change` events, the hook keeps the component's state synchronized with the media query's status. This allows developers to render different UI elements, apply varied styling, or adjust component behavior based on screen size, orientation, or other device characteristics.

Need help integrating this into your project?

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

Hire DigitalCodeLabs