react-use/src/useWindowSize.ts
xobotyi 03bdecf7ac feat(useWindowSize): A bit changed lyfecycle and added types;
feat(useWindowSize): Rewritten tests - covers more cases and will work on next @testing-library/react-hooks release (been broken before);
2019-11-03 23:13:36 +03:00

33 lines
800 B
TypeScript

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;