JAVASCRIPT

React Hook: useMediaQuery for Responsive Components

The `useMediaQuery` hook allows React components to respond to CSS media queries, enabling dynamic rendering or styling based on screen size or device features.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    const mediaQueryList = window.matchMedia(query);
    setMatches(mediaQueryList.matches);

    const listener = (event) => setMatches(event.matches);
    mediaQueryList.addEventListener('change', listener);

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

  return matches;
}

// How to use it:
/*
function ResponsiveText() {
  const isLargeScreen = useMediaQuery('(min-width: 1024px)');
  const isTablet = useMediaQuery('(min-width: 768px) and (max-width: 1023px)');

  return (
    <div>
      {isLargeScreen && <p>This text is visible on large screens.</p>}
      {isTablet && <p>This text is visible on tablets.</p>}
      {!isLargeScreen && !isTablet && <p>This text is visible on small screens.</p>}
      <p>Current screen is {isLargeScreen ? 'large' : isTablet ? 'tablet' : 'small'}.</p>
    </div>
  );
}
*/
How it works: The `useMediaQuery` hook takes a CSS media query string as an argument. It initializes a state variable with the current match status. An `useEffect` then sets up a `window.matchMedia` listener for changes to that query. When the media query status changes, the state is updated, causing the component to re-render with the correct `matches` value, allowing for responsive UI logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs