@bongsik/infinite-scroll
v0.1.0
Published
React hook for infinite scroll functionality
Maintainers
Readme
@bongsik/infinite-scroll
React hook for infinite scroll functionality using Intersection Observer API.
Installation
npm install @bongsik/infinite-scroll
# or
pnpm add @bongsik/infinite-scroll
# or
yarn add @bongsik/infinite-scrollUsage
import { useInfiniteScroll } from "@bongsik/infinite-scroll";
function MyComponent() {
const [items, setItems] = useState([]);
const [hasMore, setHasMore] = useState(true);
const [isLoading, setIsLoading] = useState(false);
const fetchMore = async () => {
setIsLoading(true);
// Fetch next page
const newItems = await fetchNextPage();
setItems((prev) => [...prev, ...newItems]);
setHasMore(newItems.length > 0);
setIsLoading(false);
};
const { sentinelRef } = useInfiniteScroll({
loadMore: fetchMore,
hasMore,
isLoading,
threshold: 100, // Load when 100px before reaching the bottom
});
return (
<div>
{items.map((item) => (
<div key={item.id}>{item.content}</div>
))}
{hasMore && <div ref={sentinelRef}>Loading...</div>}
</div>
);
}API
useInfiniteScroll(options)
Options
| Property | Type | Default | Description |
|----------|------|---------|-------------|
| loadMore | () => void \| Promise<void> | required | Function to load next page |
| hasMore | boolean | false | Whether there is more data to load |
| isLoading | boolean | false | Whether currently loading |
| threshold | number | 100 | Distance in pixels before triggering load |
| direction | "up" \| "down" | "down" | Scroll direction |
| root | HTMLElement \| null | null | Scroll container element |
| rootMargin | string | "0px" | Root margin for Intersection Observer |
Returns
| Property | Type | Description |
|----------|------|-------------|
| sentinelRef | RefObject<HTMLDivElement> | Ref to attach to sentinel element |
| loadMore | () => void | Manual function to load more |
License
MIT
