UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

50 lines (49 loc) 1.38 kB
import { useState } from "react"; import { useIsomorphicEffect } from "./useIsomorphicEffect"; var nullDimensions = { innerHeight: null, innerWidth: null, outerHeight: null, outerWidth: null, }; function getDimensions() { return { innerHeight: window.innerHeight, innerWidth: window.innerWidth, outerHeight: window.outerHeight, outerWidth: window.outerWidth, }; } /** * useWindowSize hook * A hook that provides information of the dimensions of the window * * @returns Dimensions of the window * @see https://react-hooks.org/docs/useWindowSize */ export function useWindowSize() { var _a = useState(function () { if (typeof window === "undefined") { return nullDimensions; } else { return getDimensions(); } }), windowSize = _a[0], setWindowSize = _a[1]; function onResize() { setWindowSize(getDimensions()); } // set resize handler once on mount and clean before unmount useIsomorphicEffect(function () { if (typeof window === "undefined") { return function () { }; } else { window.addEventListener("resize", onResize); return function () { window.removeEventListener("resize", onResize); }; } }, []); return windowSize; }