mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
feat(useWindowSize): Rewritten tests - covers more cases and will work on next @testing-library/react-hooks release (been broken before);
33 lines
800 B
TypeScript
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;
|