1

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?

RobertW
  • 226
  • 1
  • 2
  • 10
  • 2
    I am unable to reproduce the issue as you describe it with the above code snippet. Here's a running [codesandbpx](https://codesandbox.io/s/trying-to-fix-dependency-warning-in-react-hook-hkydgc). Maybe you could try creating a *running* codeandbox demo of your own that reproduces the issue that we could inspect live? – Drew Reese Oct 02 '22 at 21:59
  • Thanks @DrewReese makes sense ... I have deleted the answer for no more confusion ... Good learnings always from you – KcH Oct 03 '22 at 04:37

0 Answers0