Infinite Scroll RefineNext is causing infinite loop of renders

I am trying to implement infinite scroll with InfiniteHits in Algolia. I have created a useInfiniteScroll hook in React. Everything seems to work fine until esLint tells me to add refineNext as a dependency in the useEffect. The the useEffect seems to fire off in an infinite loop.

For a basic understanding of how the hook works

  • Whenever the user hit’s the last element in the array of hits, it take a ref to that
  • It then changes the intersectionObserver which in turn changes a startIndex state
  • When the startIndex changes, it fires off refineNext() which is inside a handleLoadMore function

Here is my code

const { changeObserver, startIndex, setStartIndex } = useInfiniteScroll(
    hits,
    1,
  )
  useEffect(() => {
    setStartIndex(0)
  }, [setStartIndex])

  const lastHitRef = (node) => changeObserver(node)

  function handleLoadMore() {
    if (hasMore) {
      setIsLoading(true)
      refineNext()
    }
    setIsLoading(false)
  }

  useEffect(() => {
    handleLoadMore()
  }, [startIndex, handleLoadMore])        
 // handleLoadMore breaks the app, but works fine if I remove it. I need to include this to pass esLint