All files / src/hooks useIsMobile.ts

76.19% Statements 16/21
100% Branches 4/4
50% Functions 1/2
76.19% Lines 16/21

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 281x   1x 1x   1x 10x   10x 4x   4x             4x 4x 4x 4x 4x 10x   10x 10x  
import { useEffect, useState } from 'react';
 
const MOBILE_WIDTH = 768;
const DEBOUNCE_DELAY = 150;
 
export function useIsMobile(): boolean {
  const [isMobile, setIsMobile] = useState(() => window.innerWidth < MOBILE_WIDTH);
 
  useEffect(() => {
    let timeout: NodeJS.Timeout;
 
    const handleResize = () => {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        setIsMobile(window.innerWidth < MOBILE_WIDTH);
      }, DEBOUNCE_DELAY);
    };
 
    window.addEventListener('resize', handleResize);
    return () => {
      clearTimeout(timeout);
      window.removeEventListener('resize', handleResize);
    };
  }, []);
 
  return isMobile;
}