react-use/src/useWindowSize.ts
2020-02-04 07:12:19 +05:30

34 lines
821 B
TypeScript

/* eslint-disable */
import { useEffect } from 'react';
import useRafState from './useRafState';
import { isClient } from './util';
const useWindowSize = (initialWidth = Infinity, initialHeight = Infinity) => {
const [state, setState] = useRafState<{ width: number; height: number }>({
width: isClient ? window.innerWidth : initialWidth,
height: isClient ? window.innerHeight : initialHeight,
});
useEffect((): (() => void) | void => {
if (isClient) {
const handler = () => {
setState({
width: window.innerWidth,
height: window.innerHeight,
});
};
window.addEventListener('resize', handler);
return () => {
window.removeEventListener('resize', handler);
};
}
}, []);
return state;
};
export default useWindowSize;