All files / src/hooks useIsMobile.ts

100% Statements 11/11
50% Branches 1/2
100% Functions 4/4
100% Lines 9/9

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    23x     872x           872x 276x 276x 276x 276x 276x     872x    
import { useEffect, useState } from "react";
 
const MOBILE_BREAKPOINT = 640; // Tailwind `sm:` breakpoint
 
export function useIsMobile(): boolean {
	const [isMobile, setIsMobile] = useState(
		typeof window !== "undefined"
			? window.innerWidth < MOBILE_BREAKPOINT
			: false,
	);
 
	useEffect(() => {
		const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`);
		const onChange = (e: MediaQueryListEvent) => setIsMobile(e.matches);
		mql.addEventListener("change", onChange);
		setIsMobile(mql.matches);
		return () => mql.removeEventListener("change", onChange);
	}, []);
 
	return isMobile;
}