@spaced-out/ui-design-system
Version:
Sense UI components library
42 lines (32 loc) • 1 kB
Flow
// @flow strict
import {useEffect, useState} from 'react';
import {throttle} from 'lodash';
type WindowSize = {
width: number,
height: number,
};
const THROTTLE_DURATION = 200;
export function useWindowSize(): WindowSize {
const [windowSize, setWindowSize] = useState<WindowSize>({
width: typeof window !== 'undefined' ? window.innerWidth : 0,
height: typeof window !== 'undefined' ? window.innerHeight : 0,
});
useEffect(() => {
const updateSize = throttle(() => {
const {innerWidth, innerHeight} = window;
setWindowSize((prevSize) => {
if (prevSize.width !== innerWidth || prevSize.height !== innerHeight) {
return {width: innerWidth, height: innerHeight};
}
return prevSize;
});
}, THROTTLE_DURATION);
window.addEventListener('resize', updateSize);
updateSize();
return () => {
window.removeEventListener('resize', updateSize);
updateSize.cancel();
};
}, []);
return windowSize;
}