UNPKG

@mirawision/reactive-hooks

Version:

A comprehensive collection of 50+ React hooks for state management, UI interactions, device APIs, async operations, drag & drop, audio/speech, and more. Full TypeScript support with SSR safety.

56 lines (55 loc) 1.86 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useWindowSize = useWindowSize; const react_1 = require("react"); /** * A hook that tracks window dimensions with optional throttling. * @param throttleMs Optional throttle delay in milliseconds * @returns Object containing current window width and height */ function useWindowSize(throttleMs) { const [size, setSize] = (0, react_1.useState)(() => ({ width: typeof window !== 'undefined' ? window.innerWidth : 0, height: typeof window !== 'undefined' ? window.innerHeight : 0, })); (0, react_1.useEffect)(() => { if (typeof window === 'undefined') return; let timeoutId = null; let rafId = null; const updateSize = () => { setSize({ width: window.innerWidth, height: window.innerHeight, }); }; const handleResize = () => { if (throttleMs) { // Cancel any pending updates if (timeoutId) clearTimeout(timeoutId); if (rafId) cancelAnimationFrame(rafId); timeoutId = setTimeout(() => { rafId = requestAnimationFrame(updateSize); }, throttleMs); } else { updateSize(); } }; // Initial size updateSize(); // Add event listener window.addEventListener('resize', handleResize, { passive: true }); // Cleanup return () => { window.removeEventListener('resize', handleResize); if (timeoutId) clearTimeout(timeoutId); if (rafId) cancelAnimationFrame(rafId); }; }, [throttleMs]); return size; }