think/packages/client/src/hooks/use-on-mobile.tsx

30 lines
737 B
TypeScript
Raw Normal View History

2022-05-25 05:39:01 +00:00
import { useEffect } from 'react';
2022-05-22 14:09:26 +00:00
import { createGlobalHook } from './create-global-hook';
import { useToggle } from './use-toggle';
2022-05-25 05:39:01 +00:00
const PC_MOBILE_CRITICAL_WIDTH = 765;
2022-05-22 14:09:26 +00:00
const useOnMobile = (defaultIsMobile) => {
const [isMobile, toggleIsMobile] = useToggle(defaultIsMobile);
2022-05-25 05:39:01 +00:00
useEffect(() => {
function handleResize() {
toggleIsMobile(window.innerWidth <= PC_MOBILE_CRITICAL_WIDTH);
}
window.addEventListener('resize', handleResize);
return () => {
window.removeEventListener('resize', handleResize);
};
}, [toggleIsMobile]);
2022-05-22 14:09:26 +00:00
return {
isMobile,
toggleIsMobile,
};
};
export const IsOnMobile = createGlobalHook<{ isMobile?: boolean; toggle: () => void }, boolean>(useOnMobile);