JAVASCRIPT

React `useMediaQuery` Hook for Responsive Components

Build truly responsive React components by reacting to CSS media queries dynamically with the `useMediaQuery` hook, adapting UI to screen sizes.

import { useState, useEffect } from 'react';

function useMediaQuery(query) {
  const [matches, setMatches] = useState(false);

  useEffect(() => {
    const media = window.matchMedia(query);
    if (media.matches !== matches) {
      setMatches(media.matches);
    }
    const listener = () => setMatches(media.matches);
    media.addEventListener('change', listener);
    return () => media.removeEventListener('change', listener);
  }, [matches, query]);

  return matches;
}

// Example Usage:
// function ResponsiveText() {
//   const isLargeScreen = useMediaQuery('(min-width: 768px)');
//   return (
//     <p style={{ fontSize: isLargeScreen ? '24px' : '16px' }}>
//       {isLargeScreen ? 'Large Screen Text' : 'Small Screen Text'}
//     </p>
//   );
// }
How it works: This hook allows your React components to respond to CSS media queries in real-time. It takes a media query string as input and returns a boolean indicating whether the query currently matches. It uses `window.matchMedia` and an event listener to update the state whenever the media query's status changes, enabling dynamic styling or component rendering based on screen size.

Need help integrating this into your project?

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

Hire DigitalCodeLabs