www-new/hooks/useWindowDimension.tsx

38 lines
757 B
TypeScript
Raw Normal View History

import { useEffect, useState } from "react";
interface WindowDimension {
width: number;
height: number;
}
function getWindowDimension() {
const { innerWidth: width, innerHeight: height } = window;
return {
width,
height,
};
}
export function useWindowDimension(): WindowDimension {
const [windowSize, setWindowDimension] = useState<WindowDimension>({
width: 0,
height: 0,
});
useEffect(() => {
const handleResize = () => {
setWindowDimension(getWindowDimension());
};
// Set size at the first client-side load
handleResize();
window.addEventListener("resize", handleResize);
return () => {
window.removeEventListener("resize", handleResize);
};
}, []);
return windowSize;
}