I built this React Hook to monitor the current window size so that large displayed images can be automatically resized to the space available:
import * as React from 'react';
import type { Rectangle } from 'utils/globalTypes';
/**
* This is a React Hook implementation of the window.onresize function.
*
* @param {number} horizontalMargin
* @param {number} verticalMargin
* @returns windowSize: Rectangle
*/
export const useWindowSize = (horizontalMargin: number = 0, verticalMargin: number = 0) => {
const getWindowSize = React.useCallback(() => {
const {innerWidth, innerHeight} = window;
return {width: innerWidth - horizontalMargin, height: innerHeight - verticalMargin};
}, [horizontalMargin, verticalMargin]);
const [windowSize, setWindowSize] = React.useState<Rectangle>(getWindowSize());
React.useEffect(() => {
const handleWindowResize = () => {
setWindowSize(getWindowSize());
};
window.addEventListener('resize', handleWindowResize);
return () => {
window.removeEventListener('resize', handleWindowResize); // Cleanup function
};
}, [getWindowSize]);
return [ windowSize ] as const;
};
I'm now getting this warning: Line 16:3: The 'getWindowSize' function makes the dependencies of useEffect Hook (at line 31) change on every render. To fix this, wrap the definition of 'getWindowSize' in its own useCallback() Hook react-hooks/exhaustive-deps
So, I have wrapped getWindowSize
in a useCallback
. Did I not do it correctly?