Skip to content

Instantly share code, notes, and snippets.

@mazsam
Created January 31, 2025 03:22
Show Gist options
  • Save mazsam/4328fa09503aece40e653ce9b0bbf88f to your computer and use it in GitHub Desktop.
Save mazsam/4328fa09503aece40e653ce9b0bbf88f to your computer and use it in GitHub Desktop.
import { useEffect, useState } from 'react';

const useClientMediaQuery = () => {
  const [device, setDevice] = useState({
    mobile: false,
    tablet: false,
    desktop: false,
  });

  useEffect(() => {
    const mediaQueryMobile = window.matchMedia('(max-width: 767px)');
    const mediaQueryTablet = window.matchMedia(
      '(min-width: 768px) and (max-width: 1019px)',
    );
    const mediaQueryDesktop = window.matchMedia('(min-width: 1020px)');

    const handleMatchChange = () => {
      setDevice({
        mobile: mediaQueryMobile.matches,
        tablet: mediaQueryTablet.matches,
        desktop: mediaQueryDesktop.matches,
      });
    };

    // Initial check
    handleMatchChange();

    // Add event listeners
    mediaQueryMobile.addEventListener('change', handleMatchChange);
    mediaQueryTablet.addEventListener('change', handleMatchChange);
    mediaQueryDesktop.addEventListener('change', handleMatchChange);

    // Clean up event listeners
    return () => {
      mediaQueryMobile.removeEventListener('change', handleMatchChange);
      mediaQueryTablet.removeEventListener('change', handleMatchChange);
      mediaQueryDesktop.removeEventListener('change', handleMatchChange);
    };
  }, []);

  return device;
};

export default useClientMediaQuery;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment