@supunlakmal/hooks
Version:
A collection of reusable React hooks
24 lines • 923 B
JavaScript
import * as React from 'react';
/**
* Default mobile breakpoint in pixels
*/
const DEFAULT_MOBILE_BREAKPOINT = 768;
/**
* Hook that returns whether the current viewport is mobile-sized
* @param breakpoint - Optional custom breakpoint in pixels (defaults to 768px)
* @returns boolean indicating if viewport is mobile-sized
*/
export const useMobile = (breakpoint = DEFAULT_MOBILE_BREAKPOINT) => {
const [isMobile, setIsMobile] = React.useState(undefined);
React.useEffect(() => {
const mql = window.matchMedia(`(max-width: ${breakpoint - 1}px)`);
const onChange = () => {
setIsMobile(window.innerWidth < breakpoint);
};
mql.addEventListener('change', onChange);
setIsMobile(window.innerWidth < breakpoint);
return () => mql.removeEventListener('change', onChange);
}, [breakpoint]);
return !!isMobile;
};
//# sourceMappingURL=useMobile.js.map