Back to Snippets
ReactTypeScript

React useInfiniteScroll Hook

A hook that triggers a callback when the user scrolls near the bottom of the page.

reacthookscrollpagination
import { useEffect, useCallback } from class=class="text-emerald-400">"text-emerald-400">'react'

function useInfiniteScroll(
  callback: () => void,
  options: { threshold?: number; enabled?: boolean } = {}
) {
  const { threshold = 200, enabled = true } = options

  const handleScroll = useCallback(() => {
    const scrollBottom =
      document.documentElement.scrollHeight -
      window.innerHeight -
      window.scrollY

    if (scrollBottom < threshold) {
      callback()
    }
  }, [callback, threshold])

  useEffect(() => {
    if (!enabled) return
    window.addEventListener(class=class="text-emerald-400">"text-emerald-400">'scroll', handleScroll, { passive: true })
    return () => window.removeEventListener(class=class="text-emerald-400">"text-emerald-400">'scroll', handleScroll)
  }, [handleScroll, enabled])
}

export default useInfiniteScroll

How to Use

Call in a list component: useInfiniteScroll(() => loadMore(), { threshold: 300, enabled: hasMore }). It fires the callback when the user is within 300px of the bottom. Disable it when all data is loaded.

Related Technology

React

Have a Project in Mind?

Let's discuss how we can bring your idea to life. From initial concept to production-ready product — we've got you covered.

or book a free call