Search code examples
javascriptreactjsgatsbyeslintreact-functional-component

React Hook useEffect has a missing dependency (GatsbyJs) with setInterval


I have a carousel in my component that i want to make slide independently when the component mounts, so i use useEffect()

useEffect(() => {
    const carouselTimer = setInterval(() => {
      setPage(true);
    }, 3000);
    return () => clearInterval(carouselTimer);
  }, []);

but the Gatsby ESLintError keeps throwing the warning.

warn ESLintError: 
/home/damiisdandy/Projects/Xxxxx/Xxxxxx-client/src/components/Header/Carousel/Carousel.jsx
  59:6  warning  React Hook useEffect has a missing dependency: 'setPage'. Either include it or remove
the dependency array  react-hooks/exhaustive-deps

when i place the setPage in the dependency array i get another warning.

  23:9  warning  The 'setPage' function makes the dependencies of useEffect Hook (at line 59) change on
every render. To fix this, wrap the 'setPage' definition into its own useCallback() Hook

for more information on the setPage function, this is it.

const [currentPage, setCurrentPage] = useState(0);
  const [flowDirection, setFlowDirection] = useState(true);

  const setPage = (direction) => {
    if (direction) {
      setFlowDirection(true);
      setCurrentPage((currentPage) => {
        if (currentPage === pages.length - 1) {
          return 0;
        } else {
          return currentPage + 1;
        }
      });
    } else {
      setFlowDirection(false);
      setCurrentPage((currentPage) => {
        if (currentPage === 0) {
          return pages.length - 1;
        } else {
          return currentPage - 1;
        }
      });
    }
  };

i dont know how to handle this warning (i hate seeing warnings in my code), so how can i go about it. I just want to place a setInterval when the component mounts, and clear it when it unmounts.. :(


Solution

  • try this:

    const setPage = React.useCallback((direction) => {
      if (direction) {
        setFlowDirection(true);
        setCurrentPage((currentPage) => {
          if (currentPage === pages.length - 1) {
            return 0;
          } else {
            return currentPage + 1;
          }
        });
      } else {
        setFlowDirection(false);
        setCurrentPage((currentPage) => {
          if (currentPage === 0) {
            return pages.length - 1;
          } else {
            return currentPage - 1;
          }
        });
      }
    }, [pages.length]);