UNPKG

react-window-size-listener

Version:

Minimalistic React hook for listening to window resize events with built-in debouncing.

3 lines (2 loc) 1.43 kB
import{useState as i,useEffect as e}from"react";function n(n={}){const{debounceTime:w=100}=n,[t,o]=i(()=>"undefined"!=typeof window?{width:window.innerWidth,height:window.innerHeight}:{width:0,height:0});return e(()=>{if("undefined"==typeof window)return;let i=null;const e=()=>{i&&window.clearTimeout(i),i=window.setTimeout(()=>{o({width:window.innerWidth,height:window.innerHeight})},w)};return window.addEventListener("resize",e),()=>{window.removeEventListener("resize",e),i&&window.clearTimeout(i)}},[w]),t}function w(n={}){const{debounceTime:w=100}=n,[t,o]=i(()=>"undefined"==typeof window?{width:0,height:0}:window.visualViewport?{width:window.visualViewport.width,height:window.visualViewport.height}:{width:window.innerWidth,height:window.innerHeight});return e(()=>{if("undefined"==typeof window)return;let i=null;const e=()=>{i&&window.clearTimeout(i),i=window.setTimeout(()=>{window.visualViewport?o({width:window.visualViewport.width,height:window.visualViewport.height}):o({width:window.innerWidth,height:window.innerHeight})},w)},n=window.visualViewport||window;return n.addEventListener("resize",e),window.visualViewport&&window.visualViewport.addEventListener("scroll",e),()=>{n.removeEventListener("resize",e),window.visualViewport&&window.visualViewport.removeEventListener("scroll",e),i&&window.clearTimeout(i)}},[w]),t}export{w as useViewportSize,n as useWindowSize}; //# sourceMappingURL=index.modern.mjs.map