Home > Software engineering >  TypeScript error for react-hooks/exhaustive-deps
TypeScript error for react-hooks/exhaustive-deps

Time:04-26

New to TypeScript & React so bear with me, but getting:

Warning: React Hook useEffect has a missing dependency: 'action'. Either include it or remove the dependency array. If 'action' changes too often, find the parent component that defines it and wrap that definition in useCallback.  react-hooks/exhaustive-deps

for:

function useHandleOutsideClick(ref, action: () => void) {
  useEffect(() => {
    function handleClickOutside(event) {
      if (ref.current && !ref.current.contains(event.target)) {
        action();
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [ref]);
}

Not sure if it matters, but this sits outside of the actual component export.

Doing some reading on useCallback & I attempted to move handleClickOutside outside of useHandleOutsideClick, but then got a missing parameter for event:

const handleClickOutside = useCallback(
  (event, ref, action) => {
    if (ref.current && !ref.current.contains(event.target)) {
      action();
    }
  },
  [ref]
);

function useHandleOutsideClick(ref, action: () => void) {
  useEffect(() => {
    handleClickOutside(event, ref, action);

    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [ref]);
}

But then got missing ref. Feels like I'm missing something simple.

CodePudding user response:

You must add action to the list of dependencies if you want to use this inside useEffect.

For example:

useEffect(() => {
  /* ... */
}, [ref, action]); // dependencies
  • Related