UNPKG

@gravitywelluk/react-hooks

Version:
73 lines (72 loc) 2.76 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); __setModuleDefault(result, mod); return result; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.useWindowDimensions = void 0; const React = __importStar(require("react")); // Initial window dimensions const initialWindowDimensions = { width: undefined, height: undefined }; /** * Window dimensions hook */ const useWindowDimensions = () => { const isClient = typeof window === "object"; const [initialised, setInitialised] = React.useState(false); const [windowDimensions, setWindowDimensions] = React.useState(initialWindowDimensions); /** * Updates the window dimensions when called */ const updateWindowDimensions = React.useCallback(() => { setWindowDimensions({ height: isClient ? window.innerHeight : undefined, width: isClient ? window.innerWidth : undefined }); }, [isClient]); // On isClient change, attempt to set the window dimensions and add "reize" // event listeners. React.useEffect(() => { // If window client exists and the dimensions have not been initialised, // set them and update state. if (isClient && !initialised) { // Update the initialised state setInitialised(true); // Initialise the updateWindowDimensions(); // Add "resize" event listener window.addEventListener("resize", updateWindowDimensions); } // On unmount, remove the "resize" event listener return () => { // If window client exists and the dimensions have been initialised if (isClient && initialised) { window.removeEventListener("resize", updateWindowDimensions); } }; }, [ initialised, isClient, updateWindowDimensions ]); return windowDimensions; }; exports.useWindowDimensions = useWindowDimensions;