UNPKG

@carbon/ibm-products

Version:

Carbon for IBM Products

70 lines (64 loc) 1.66 kB
/** * Copyright IBM Corp. 2020, 2025 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; var React = require('react'); const windowExists = typeof window !== `undefined`; const getWindowSize = () => { if (!windowExists) { return { innerHeight: 0, innerWidth: 0, outerHeight: 0, outerWidth: 0 }; } const { innerHeight, innerWidth, outerHeight, outerWidth } = { ...window }; return { innerHeight, innerWidth, outerHeight, outerWidth }; }; const useWindowResize = function (effect, deps) { let throttleInterval = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; const windowSize = React.useRef({}); const throttleTimeout = React.useRef(null); const doGetWindowSize = () => { const newVal = { previous: windowSize.current, current: getWindowSize() }; // call effect effect(newVal); windowSize.current = newVal.current; throttleTimeout.current = null; }; React.useLayoutEffect(() => { const handleResize = () => { if (throttleInterval) { if (throttleTimeout.current === null) { throttleTimeout.current = setTimeout(doGetWindowSize, throttleInterval); } } else { doGetWindowSize(); } }; window.addEventListener('resize', handleResize); doGetWindowSize(); return () => window.removeEventListener('resize', handleResize); // eslint-disable-next-line react-hooks/exhaustive-deps }, deps); }; exports.useWindowResize = useWindowResize;