use-mobile.ts
1 import * as React from 'react'; 2 3 const MOBILE_BREAKPOINT = 768; 4 5 export function useIsMobile() { 6 const [isMobile, setIsMobile] = React.useState<boolean | undefined>( 7 undefined, 8 ); 9 10 React.useEffect(() => { 11 const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`); 12 const onChange = () => { 13 setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); 14 }; 15 mql.addEventListener('change', onChange); 16 setIsMobile(window.innerWidth < MOBILE_BREAKPOINT); 17 return () => mql.removeEventListener('change', onChange); 18 }, []); 19 20 return !!isMobile; 21 }