JAVASCRIPT

React `useMediaQuery` Hook for Responsive Design

A custom React hook that allows components to reactively respond to CSS media queries, enabling dynamic styling or rendering based on screen size or device features.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    if (typeof window.matchMedia !== 'function') {
      // Fallback for environments without window.matchMedia (e.g., SSR)
      return;
    }

    const mediaQueryList = window.matchMedia(query);
    const listener = (event) => setMatches(event.matches);

    setMatches(mediaQueryList.matches); // Initial check
    mediaQueryList.addEventListener('change', listener);

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

  return matches;
};

export default useMediaQuery;

/* Example Usage:
import React from 'react';

function MyResponsiveComponent() {
  const isLargeScreen = useMediaQuery('(min-width: 1024px)');
  const isDarkPreferred = useMediaQuery('(prefers-color-scheme: dark)');

  return (
    <div>
      {isLargeScreen ? 'You are on a large screen.' : 'You are on a small screen.'}
      <p>Dark mode preferred: {isDarkPreferred ? 'Yes' : 'No'}</p>
    </div>
  );
}
*/
How it works: This hook takes a CSS media query string and returns a boolean indicating whether the query currently matches. It uses `window.matchMedia` and its `addEventListener` to listen for changes in the media query status, updating the component's state reactively. This is perfect for dynamic responsive design in React.

Need help integrating this into your project?

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

Hire DigitalCodeLabs