JAVASCRIPT

Respond to CSS Media Queries in React with useMediaQuery Hook

Custom React hook `useMediaQuery` allows components to react to CSS media queries, enabling dynamic styling or rendering based on screen size.

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    if (typeof window === 'undefined' || !window.matchMedia) {
      return; // For SSR environments where window is not available
    }

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

    // Initial check
    setMatches(mediaQueryList.matches);

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

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

  return matches;
}
How it works: This hook takes a CSS media query string (e.g., `(min-width: 768px)`). It initializes its `matches` state based on the current evaluation of the media query. An `useEffect` hook then sets up an event listener using the `window.matchMedia` API to update the `matches` state whenever the media query status changes (e.g., when the viewport size crosses a breakpoint). This makes your React component dynamically reactive to viewport changes, allowing for conditional rendering or styling based on screen dimensions, and includes a safeguard for server-side rendering.

Need help integrating this into your project?

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

Hire DigitalCodeLabs