react-use/src/useWindowSize.ts
Renovate Bot a27f09fd36
chore: refactoring and rearrangement.
More DRY code. Also move non-hooks to separate directories.

BREAKING CHANGE: all `create*` factories been moved to `factory` subdirectory and in case direct import should be imported like `react-use/esm/factory/createBreakpoint`
BREAKING CHANGE: `comps` directory renamed to `component`
2021-01-30 23:30:26 +03:00

33 lines
790 B
TypeScript

import { useEffect } from 'react';
import useRafState from './useRafState';
import { isBrowser, off, on } from './misc/util';
const useWindowSize = (initialWidth = Infinity, initialHeight = Infinity) => {
const [state, setState] = useRafState<{ width: number; height: number }>({
width: isBrowser ? window.innerWidth : initialWidth,
height: isBrowser ? window.innerHeight : initialHeight,
});
useEffect((): (() => void) | void => {
if (isBrowser) {
const handler = () => {
setState({
width: window.innerWidth,
height: window.innerHeight,
});
};
on(window, 'resize', handler);
return () => {
off(window, 'resize', handler);
};
}
}, []);
return state;
};
export default useWindowSize;