Infinite loop with useEffect and useCallback

Asked

Viewed 417 times

1

As code below, I need to call a function whenever inView is true, but using useEffect and useCallback listing the dependencies, I cause an infinite loop. The only ways I could avoid were without listing the dependencies, but I get a Warning warning that I have to list them. I tried only with useEffect, but the result is the same, listing the dependencies, I have problem with the loops. Follow the code:

    import { useEffect, useCallback } from "react";
    import { useInView } from "react-intersection-observer";
    
    export const useLazyLoader = (onEnterView: () => void) => {
      const [ref, inView] = useInView({
        triggerOnce: true,
        rootMargin: "-200px",
      });
    
      const innerEnterView = useCallback(() => {
        onEnterView();
      }, [onEnterView]);
    
      useEffect(() => {
        inView && innerEnterView();
      }, [inView, innerEnterView]);
      return ref;
    };

In this example, if I remove any of the dependencies to try to avoid the problem, I end up getting Warning like this:

Line 16:6:  React Hook useEffect has a missing dependency: 'innerEnterView'. Either include it or remove the dependency array  react-hooks/exhaustive-deps
  • Hard to know it seems that the function is in the loop inside the useEffect

1 answer

1

About the useCallback itself documentation says that:

This is useful when we use callbacks to optimize components children

but the callback is not being passed to a child component. So the correct use of it would be that the property onEnterView is already received as a callback.

  • Sorry for the delay, I managed to resolve encapsulating onEnderView in a useCallback before moving to the hook

Browser other questions tagged

You are not signed in. Login or sign up in order to post.