High-performance infinite scroll hook for React
npm install @windowing-kit/infinite-scrollHigh-performance infinite scroll hook for React using the Intersection Observer API.
``bash`
npm install @windowing-kit/infinite-scrollor
pnpm add @windowing-kit/infinite-scrollor
yarn add @windowing-kit/infinite-scroll
`tsx
import { useInfiniteScroll } from "@windowing-kit/infinite-scroll";
import { useInfiniteState } from "./useInfiniteState";
function MyInfiniteList() {
const { items, hasNextPage, loading, fetchData } = useInfiniteState();
const { ref, isFetching } = useInfiniteScroll({
loading,
hasNextPage,
onLoadMore: fetchData,
rootMargin: "200px",
initialLoad: true,
});
return (
API
$3
Infinite scroll hook.
#### Options
| Property | Type | Required | Default | Description |
| ------------- | ----------------------------- | -------- | ------- | ---------------------------------------------------- |
|
loading | boolean | Yes | - | Whether data is currently being loaded |
| hasNextPage | boolean | Yes | - | Whether there is more data to load |
| onLoadMore | () => void \| Promise | Yes | - | Callback function to load more data |
| rootMargin | string | No | "0px" | Root margin for Intersection Observer |
| disabled | boolean | No | false | Whether to disable infinite scroll |
| delayInMs | number | No | 100 | Delay in milliseconds before triggering onLoadMore |
| initialLoad | boolean | No | false | Whether to automatically load data on initial mount |#### Return
| Property | Type | Description |
| ------------ | ----------------------- | --------------------------------------------------------------------------------- |
|
ref | VisibilityRefCallback | Ref callback to attach to the trigger element (usually the last item or sentinel) |
| isFetching | boolean | Whether data is currently being fetched (same as loading) |Examples
$3
`tsx
function InfiniteList() {
const { items, hasNextPage, loading, fetchData } = useInfiniteState(); const { ref, isFetching } = useInfiniteScroll({
loading,
hasNextPage,
onLoadMore: fetchData,
});
return (
{items.map((item) => (
))}
{isFetching && }
);
}
`$3
`tsx
const { ref, isFetching } = useInfiniteScroll({
loading,
hasNextPage,
onLoadMore: loadMore,
rootMargin: "300px", // Start loading 300px before reaching the bottom
});
`$3
`tsx
const { ref, isFetching } = useInfiniteScroll({
loading,
hasNextPage,
onLoadMore: loadMore,
disabled: !user.isAuthenticated, // Disable if user is not authenticated
});
`$3
`tsx
const { ref, isFetching } = useInfiniteScroll({
loading,
hasNextPage,
onLoadMore: loadMore,
initialLoad: true, // Automatically load data when component mounts
});
``