Docs
useInfiniteScroll

Implement infinite scrolling functionality with the useInfiniteScroll hook, allowing for dynamic loading of content as the user scrolls.

Loading...

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-infinite-scroll

Usage

"use client"
 
import { useInfiniteScroll } from "@/hooks/use-infinite-scroll"
 
export function Component() {
  const { ref, onLoadMore, isLoading, hasMore } = useInfiniteScroll({
    onLoadMore: () => {
      console.log("Loading more content...")
      // Simulate loading more content
      setTimeout(() => {
        console.log("More content loaded")
      }, 1000)
    },
    isLoading: false,
    hasMore: true,
    threshold: 100,
  })
 
  return (
    <div
      ref={ref}
      style={{
        height: "400px",
        overflowY: "auto",
        padding: "20px",
        border: "1px solid #ccc",
      }}
    >
      <p>Scroll down to load more content...</p>
      <div style={{ height: "800px" }}>
        {/* Simulated content */}
        {Array.from({ length: 20 }, (_, i) => (
          <p key={i}>Item {i + 1}</p>
        ))}
      </div>
      {isLoading && <p>Loading...</p>}
      {!hasMore && <p>No more content to load.</p>}
    </div>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
onLoadMore() => voidCallback function to load more content when the user scrolls near the bottom of the page.-No
isLoadingbooleanIndicates whether content is currently being loaded. This can be used to prevent multiple load requests.falseYes
hasMorebooleanIndicates whether there is more content to load. If false, the hook will not trigger further loading.trueYes
thresholdnumberThe distance from the bottom of the page at which to trigger loading more content. Default is 100.100Yes

Return Values

NameTypeDescription
refReact.RefObject<HTMLDivElement | null>A ref to be attached to the scrollable container. This is used to monitor the scroll position and trigger loading more content.