JAVASCRIPT

Reacting to CSS Media Queries with useMediaQuery Hook

Develop a useMediaQuery React hook to programmatically detect CSS media query matches, enabling dynamic and responsive UI components in JavaScript based on screen size.

import React, { 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 state
    setMatches(mediaQueryList.matches);

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

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

  return matches;
}

// Example usage:
function ResponsiveComponent() {
  const isLargeScreen = useMediaQuery('(min-width: 1024px)');
  const isMobile = useMediaQuery('(max-width: 768px)');

  return (
    <div>
      {isLargeScreen && <p>This content is visible on large screens.</p>}
      {isMobile && <p>This content is visible on mobile devices.</p>}
      {!isLargeScreen && !isMobile && <p>This content is visible on medium screens.</p>}
    </div>
  );
}

export default ResponsiveComponent;
How it works: The `useMediaQuery` hook enables React components to respond to CSS media queries programmatically. It takes a media query string (e.g., `'(min-width: 768px)'`) and returns a boolean indicating whether the query currently matches. It uses `window.matchMedia` to create a `MediaQueryList` object and `addEventListener` to listen for changes. The `useEffect` hook ensures that the listener is properly set up and torn down, keeping the component's state synchronized with the media query's status.

Need help integrating this into your project?

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

Hire DigitalCodeLabs