useIsMobile.js 446 B

123456789101112131415
  1. export const MOBILE_BREAKPOINT = 768;
  2. import { useSyncExternalStore } from 'react';
  3. export const useIsMobile = () => {
  4. const query = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`;
  5. return useSyncExternalStore(
  6. (callback) => {
  7. const mql = window.matchMedia(query);
  8. mql.addEventListener('change', callback);
  9. return () => mql.removeEventListener('change', callback);
  10. },
  11. () => window.matchMedia(query).matches,
  12. );
  13. };