All files / hook useIsMobile.ts

100% Statements 12/12
100% Branches 0/0
100% Functions 4/4
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 303x                             3x 4x   4x 3x 4x   3x   3x 3x     4x  
import { useEffect, useState } from 'react';
 
/**
 * @group Hooks
 */
 
/**
 * Hook personnalisé pour détecter si l'utilisateur est sur un appareil mobile
 * @returns {boolean} true si l'écran fait moins de 768px de large, false sinon
 * @example
 * const isMobile = useIsMobile();
 * if (isMobile) {
 *   // Afficher la version mobile
 * }
 */
export default function useIsMobile(): boolean {
  const [isMobile, setIsMobile] = useState(false);
 
  useEffect(() => {
    const mediaQuery = window.matchMedia('(max-width: 767px)');
    const updateMatch = () => setIsMobile(mediaQuery.matches);
 
    updateMatch()
 
    mediaQuery.addEventListener('change', updateMatch);
    return () => mediaQuery.removeEventListener('change', updateMatch);
  }, []);
 
  return isMobile;
}