react-infinite-scroll-component、react-infinite-scroller、react-window-infinite-loader は、React アプリケーションで無限スクロール機能を実装するためのライブラリです。これらは大量のデータを効率的に表示し、ユーザーがスクロールするたびに新しいデータを読み込む仕組みを提供しますが、アプローチと性能特性が異なります。react-infinite-scroll-component はシンプルさを重視し、react-infinite-scroller は軽量な実装を提供し、react-window-infinite-loader は react-window と連携して仮想化による高性能を実現します。
react-infinite-scroll-component、react-infinite-scroller、react-window-infinite-loader は、React で無限スクロールを実装する代表的なライブラリですが、根本的なアプローチが異なります。実際の開発現場で直面する問題にどう対応するか、技術的な観点から比較します。
react-infinite-scroll-component は DOM にすべてのアイテムをレンダリングします。
// react-infinite-scroll-component: 全アイテムをレンダリング
import InfiniteScroll from 'react-infinite-scroll-component';
function UserList({ users, fetchMore, hasMore }) {
return (
<InfiniteScroll
dataLength={users.length}
next={fetchMore}
hasMore={hasMore}
loader={<h4>読み込み中...</h4>}
>
{users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</InfiniteScroll>
);
}
react-infinite-scroller も同様に全アイテムをレンダリングします。
// react-infinite-scroller: 全アイテムをレンダリング
import InfiniteScroll from 'react-infinite-scroller';
function UserList({ users, fetchMore, hasMore }) {
return (
<InfiniteScroll
pageStart={0}
loadMore={fetchMore}
hasMore={hasMore}
loader={<div key={0}>読み込み中...</div>}
>
{users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</InfiniteScroll>
);
}
react-window-infinite-loader は仮想化を使用して表示中のアイテムのみをレンダリングします。
react-window と連携して高性能を実現// react-window-infinite-loader: 仮想化で表示中のみのレンダリング
import InfiniteLoader from 'react-window-infinite-loader';
import { FixedSizeList } from 'react-window';
function UserList({ users, fetchMore, hasMore }) {
const isItemLoaded = index => !hasMore || index < users.length;
return (
<InfiniteLoader
isItemLoaded={isItemLoaded}
itemCount={hasMore ? users.length + 1 : users.length}
loadMoreItems={fetchMore}
>
{({ onItemsRendered, ref }) => (
<FixedSizeList
height={600}
itemCount={users.length}
itemSize={50}
onItemsRendered={onItemsRendered}
ref={ref}
>
{({ index, style }) => (
<div style={style} key={users[index]?.id}>
{users[index]?.name || '読み込み中...'}
</div>
)}
</FixedSizeList>
)}
</InfiniteLoader>
);
}
データの状態管理方法もライブラリ間で異なります。
react-infinite-scroll-component は親コンポーネントで状態を管理します。
dataLength props で現在のアイテム数を通知// react-infinite-scroll-component: 親で状態管理
function UserList() {
const [users, setUsers] = useState([]);
const [page, setPage] = useState(1);
const fetchMore = async () => {
const newUsers = await api.getUsers(page + 1);
setUsers([...users, ...newUsers]);
setPage(page + 1);
};
return (
<InfiniteScroll
dataLength={users.length}
next={fetchMore}
hasMore={users.length < total}
>
{users.map(user => <UserCard key={user.id} user={user} />)}
</InfiniteScroll>
);
}
react-infinite-scroller も同様に親コンポーネントで状態を管理します。
pageStart で現在のページを追跡// react-infinite-scroller: 親で状態管理
function UserList() {
const [users, setUsers] = useState([]);
const [page, setPage] = useState(0);
const fetchMore = async () => {
const newUsers = await api.getUsers(page + 1);
setUsers([...users, ...newUsers]);
setPage(page + 1);
};
return (
<InfiniteScroll
pageStart={page}
loadMore={fetchMore}
hasMore={users.length < total}
>
{users.map(user => <UserCard key={user.id} user={user} />)}
</InfiniteScroll>
);
}
react-window-infinite-loader はアイテムのロード状態をライブラリが管理します。
isItemLoaded で各アイテムのロード状態を判定loadMoreItems がバッチ処理をサポート// react-window-infinite-loader: ライブラリがロード状態を管理
function UserList() {
const [users, setUsers] = useState({});
const isItemLoaded = index => users[index] !== undefined;
const loadMoreItems = async ({ startIndex, stopIndex }) => {
const newUsers = await api.getUsers(startIndex, stopIndex);
setUsers(prev => ({ ...prev, ...newUsers }));
};
return (
<InfiniteLoader
isItemLoaded={isItemLoaded}
itemCount={total}
loadMoreItems={loadMoreItems}
>
{({ onItemsRendered, ref }) => (
<FixedSizeList
height={600}
itemCount={total}
itemSize={50}
onItemsRendered={onItemsRendered}
ref={ref}
>
{({ index, style }) => (
<div style={style} key={index}>
{users[index]?.name || '読み込み中...'}
</div>
)}
</FixedSizeList>
)}
</InfiniteLoader>
);
}
パフォーマンスは無限スクロール実装で最も重要な考慮事項です。
react-infinite-scroll-component のパフォーマンス特性:
// react-infinite-scroll-component: 大量データでの注意点
function UserList() {
const [users, setUsers] = useState([]);
// ⚠️ 10000 件を超えるとパフォーマンス低下のリスク
const fetchMore = async () => {
if (users.length > 5000) {
console.warn('パフォーマンス低下の可能性があります');
}
const newUsers = await api.getUsers(users.length);
setUsers([...users, ...newUsers]);
};
return (
<InfiniteScroll
dataLength={users.length}
next={fetchMore}
hasMore={true}
scrollThreshold={0.9} // 90% スクロールでトリガー
>
{users.map(user => <UserCard key={user.id} user={user} />)}
</InfiniteScroll>
);
}
react-infinite-scroller のパフォーマンス特性:
react-infinite-scroll-component と同様の制限// react-infinite-scroller: 性能制限への対応
function UserList() {
const [users, setUsers] = useState([]);
const fetchMore = async () => {
// ⚠️ 大量データでは仮想化ライブラリの使用を検討
if (users.length > 3000) {
console.warn('react-window-infinite-loader への移行を検討してください');
}
const newUsers = await api.getUsers(users.length);
setUsers([...users, ...newUsers]);
};
return (
<InfiniteScroll
pageStart={0}
loadMore={fetchMore}
hasMore={users.length < total}
useWindow={true} // window スクロールを使用
>
{users.map(user => <UserCard key={user.id} user={user} />)}
</InfiniteScroll>
);
}
react-window-infinite-loader のパフォーマンス特性:
// react-window-infinite-loader: 大規模データに最適化
function UserList() {
const [users, setUsers] = useState({});
const TOTAL_ITEMS = 100000;
const isItemLoaded = index => users[index] !== undefined;
const loadMoreItems = async ({ startIndex, stopIndex }) => {
// バッチ処理で効率的にデータ取得
const newUsers = await api.getUsersBatch(startIndex, stopIndex);
setUsers(prev => ({ ...prev, ...newUsers }));
};
return (
<InfiniteLoader
isItemLoaded={isItemLoaded}
itemCount={TOTAL_ITEMS}
loadMoreItems={loadMoreItems}
minimumBatchSize={10} // 一度にロードする最小アイテム数
>
{({ onItemsRendered, ref }) => (
<FixedSizeList
height={600}
itemCount={TOTAL_ITEMS}
itemSize={50}
onItemsRendered={onItemsRendered}
ref={ref}
overscanCount={5} // 表示範囲外のバッファ
>
{({ index, style }) => (
<div style={style} key={index}>
{users[index]?.name || '読み込み中...'}
</div>
)}
</FixedSizeList>
)}
</InfiniteLoader>
);
}
実務ではページ遷移後にスクロール位置を保持する必要がある場合があります。
react-infinite-scroll-component はスクロール位置の保持が容易です。
scrollTop を直接制御可能// react-infinite-scroll-component: スクロール位置保持
function UserList() {
const scrollRef = useRef(null);
const [scrollPosition, setScrollPosition] = useState(0);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollPosition;
}
}, []);
const handleScroll = () => {
if (scrollRef.current) {
setScrollPosition(scrollRef.current.scrollTop);
}
};
return (
<div
ref={scrollRef}
onScroll={handleScroll}
style={{ height: '600px', overflow: 'auto' }}
>
<InfiniteScroll
dataLength={users.length}
next={fetchMore}
hasMore={hasMore}
scrollableTarget={scrollRef.current}
>
{users.map(user => <UserCard key={user.id} user={user} />)}
</InfiniteScroll>
</div>
);
}
react-infinite-scroller も同様にスクロール位置を制御できます。
useWindow props で window/要素スクロールを切り替えgetScrollParent で制御// react-infinite-scroller: スクロール位置保持
function UserList() {
const containerRef = useRef(null);
useEffect(() => {
if (containerRef.current) {
containerRef.current.scrollTop = savedPosition;
}
}, []);
return (
<div ref={containerRef} style={{ height: '600px', overflow: 'auto' }}>
<InfiniteScroll
pageStart={0}
loadMore={fetchMore}
hasMore={hasMore}
useWindow={false} // 要素スクロールを使用
getScrollParent={() => containerRef.current}
>
{users.map(user => <UserCard key={user.id} user={user} />)}
</InfiniteScroll>
</div>
);
}
react-window-infinite-loader は仮想化のためスクロール位置の制御が特殊です。
scrollToItem メソッドを使用// react-window-infinite-loader: スクロール位置保持
function UserList() {
const listRef = useRef(null);
const targetIndex = useRef(0);
useEffect(() => {
if (listRef.current && targetIndex.current > 0) {
listRef.current.scrollToItem(targetIndex.current, 'start');
}
}, [users]);
return (
<InfiniteLoader
isItemLoaded={isItemLoaded}
itemCount={total}
loadMoreItems={loadMoreItems}
>
{({ onItemsRendered, ref }) => (
<FixedSizeList
height={600}
itemCount={total}
itemSize={50}
onItemsRendered={onItemsRendered}
ref={listRef}
>
{({ index, style }) => (
<div style={style} key={index}>
{users[index]?.name || '読み込み中...'}
</div>
)}
</FixedSizeList>
)}
</InfiniteLoader>
);
}
ローディング状態や終了時の表示も重要な UX 要素です。
react-infinite-scroll-component のカスタマイズ:
loader props でローディング表示を指定endMessage props で終了メッセージを表示// react-infinite-scroll-component: UI カスタマイズ
<InfiniteScroll
dataLength={users.length}
next={fetchMore}
hasMore={hasMore}
loader={
<div className="loader">
<Spinner />
<p>データを読み込んでいます...</p>
</div>
}
endMessage={
<div className="end-message">
<p>🎉 全てのデータを表示しました</p>
</div>
}
pullDownToRefresh={true}
refreshFunction={handleRefresh}
>
{users.map(user => <UserCard key={user.id} user={user} />)}
</InfiniteScroll>
react-infinite-scroller のカスタマイズ:
loader props でローディング表示を指定// react-infinite-scroller: UI カスタマイズ
<InfiniteScroll
pageStart={0}
loadMore={fetchMore}
hasMore={hasMore}
loader={
<div className="loader" key={0}>
<Spinner />
<p>データを読み込んでいます...</p>
</div>
}
>
{users.map(user => <UserCard key={user.id} user={user} />)}
{!hasMore && (
<div className="end-message" key="end">
<p>🎉 全てのデータを表示しました</p>
</div>
)}
</InfiniteScroll>
react-window-infinite-loader のカスタマイズ:
// react-window-infinite-loader: UI カスタマイズ
<InfiniteLoader
isItemLoaded={isItemLoaded}
itemCount={hasMore ? users.length + 1 : users.length}
loadMoreItems={fetchMore}
>
{({ onItemsRendered, ref }) => (
<FixedSizeList
height={600}
itemCount={hasMore ? users.length + 1 : users.length}
itemSize={50}
onItemsRendered={onItemsRendered}
ref={ref}
>
{({ index, style }) => {
if (index >= users.length) {
return (
<div style={style} key="loader">
<Spinner />
<p>データを読み込んでいます...</p>
</div>
);
}
return (
<div style={style} key={users[index].id}>
<UserCard user={users[index]} />
</div>
);
}}
</FixedSizeList>
)}
</InfiniteLoader>
これらのライブラリには多くの共通点もあります。
// 3 ライブラリ共通:React コンポーネントとして使用
function UserList({ users, fetchMore, hasMore }) {
// どのライブラリでも同様のパターンで使用可能
return (
<InfiniteScrollComponent
// 各ライブラリの props を設定
>
{users.map(user => <UserCard key={user.id} user={user} />)}
</InfiniteScrollComponent>
);
}
useWindow または scrollableTarget で制御// window スクロールの場合
<InfiniteScroll useWindow={true}>
{/* 内容 */}
</InfiniteScroll>
// 要素スクロールの場合
<div style={{ height: '600px', overflow: 'auto' }}>
<InfiniteScroll useWindow={false}>
{/* 内容 */}
</InfiniteScroll>
</div>
next、loadMore、loadMoreItems でデータ取得をトリガー// 3 ライブラリ共通:非同期データ読み込みパターン
const fetchMore = async () => {
try {
const newItems = await api.getData(page);
setItems([...items, ...newItems]);
} catch (error) {
console.error('データ取得エラー:', error);
// エラー状態の管理は開発者側で
}
};
// TypeScript での使用例(3 ライブラリ共通)
interface User {
id: number;
name: string;
}
interface Props {
users: User[];
fetchMore: () => Promise<void>;
hasMore: boolean;
}
function UserList({ users, fetchMore, hasMore }: Props) {
// 型チェックが機能
}
scrollThreshold props で制御// スクロール閾値の設定(対応ライブラリ)
<InfiniteScroll
scrollThreshold={0.8} // 80% スクロールでトリガー
// 早期読み込みでユーザー待機時間を削減
>
{/* 内容 */}
</InfiniteScroll>
| 機能 | react-infinite-scroll-component | react-infinite-scroller | react-window-infinite-loader |
|---|---|---|---|
| 仮想化 | ❌ 全アイテムレンダリング | ❌ 全アイテムレンダリング | ✅ 表示中のみのレンダリング |
| 最大推奨アイテム数 | ~1000 件 | ~1000 件 | 10 万件以上 |
| メモリ使用量 | データ量に比例 | データ量に比例 | 一定 |
| 実装の複雑さ | 低 | 低 | 中〜高 |
| スクロール位置保持 | 容易 | 容易 | 特殊な制御が必要 |
| メンテナンス状況 | 活発 | 要注意 | 活発 |
| 依存関係 | 軽量 | 軽量 | react-window が必要 |
データ量とパフォーマンス要件で選択しましょう:
react-infinite-scroll-component(シンプルで十分)react-infinite-scroller(変更コストを考慮)react-window-infinite-loader(性能が最優先)react-window-infinite-loader(安定性と拡張性)重要なポイント:無限スクロール実装では、初期の開発速度よりも長期的なパフォーマンスとメンテナンス性を重視すべきです。プロジェクトの規模と成長を見据えて、適切なライブラリを選択しましょう。
react-infinite-scroll-component を選択するのは、シンプルな実装で十分な場合や、仮想化の複雑さを避けたいプロジェクトです。メンテナンスが活発で API が直感的ですが、大量のデータ(1000 件以上)をレンダリングするとパフォーマンスが低下する可能性があります。小〜中規模のリストや、プロトタイプ開発に適しています。
react-window-infinite-loader を選択するのは、大規模なデータセット(数千件以上)を扱う場合や、パフォーマンスが最優先事項の場合です。react-window と連携して仮想化を実現し、表示されているアイテムのみをレンダリングするため、メモリ使用量と描画コストを大幅に削減できます。エンタープライズアプリケーションやデータ密集型プロジェクトに最適です。
react-infinite-scroller を選択するのは、軽量な依存関係とシンプルな API を優先する場合です。ただし、メンテナンス状況に注意が必要で、新しいプロジェクトでは慎重に評価すべきです。既存プロジェクトの維持や、仮想化が不要なシンプルなユースケースに適しています。
Infinite scroll for React. Zero runtime dependencies, IntersectionObserver-based, TypeScript-first. ~4 kB gzipped.
Works with window scroll, fixed-height containers, and custom scrollable parents. Pull-to-refresh and inverse (chat) scroll included. React 17, 18, and 19 compatible.
npm install react-infinite-scroll-component
# or
yarn add react-infinite-scroll-component
# or
pnpm add react-infinite-scroll-component
| API | When to use |
|---|---|
InfiniteScroll component | Most cases, handles loader, endMessage, pull-to-refresh, inverse scroll UI |
useInfiniteScroll hook | Custom UI, you own the markup, the hook manages the observer |
InfiniteScroll componentimport { useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
type Item = { id: number; name: string };
function Feed() {
const [items, setItems] = useState<Item[]>(initialItems);
const [hasMore, setHasMore] = useState(true);
const fetchMore = async () => {
const next = await api.getItems({ offset: items.length });
if (next.length === 0) {
setHasMore(false);
return;
}
setItems((prev) => [...prev, ...next]);
};
return (
<InfiniteScroll
dataLength={items.length}
next={fetchMore}
hasMore={hasMore}
loader={<p>Loading...</p>}
endMessage={<p style={{ textAlign: 'center' }}>All items loaded.</p>}
>
{items.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</InfiniteScroll>
);
}
<div id="scrollableDiv" style={{ height: 400, overflow: 'auto' }}>
<InfiniteScroll
dataLength={items.length}
next={fetchMore}
hasMore={hasMore}
loader={<p>Loading...</p>}
scrollableTarget="scrollableDiv"
>
{items.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</InfiniteScroll>
</div>
Pass a ref value directly instead of a string id:
const containerRef = useRef<HTMLDivElement>(null);
<div ref={containerRef} style={{ height: 400, overflow: 'auto' }}>
<InfiniteScroll
dataLength={items.length}
next={fetchMore}
hasMore={hasMore}
loader={<p>Loading...</p>}
scrollableTarget={containerRef.current}
>
{items.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</InfiniteScroll>
</div>;
<div
id="chatBox"
style={{
height: 500,
overflow: 'auto',
display: 'flex',
flexDirection: 'column-reverse',
}}
>
<InfiniteScroll
dataLength={messages.length}
next={loadOlderMessages}
hasMore={hasMore}
loader={<p>Loading older messages...</p>}
inverse={true}
scrollableTarget="chatBox"
style={{ display: 'flex', flexDirection: 'column-reverse' }}
>
{messages.map((msg) => (
<div key={msg.id}>{msg.text}</div>
))}
</InfiniteScroll>
</div>
<InfiniteScroll
dataLength={items.length}
next={fetchMore}
hasMore={hasMore}
loader={<p>Loading...</p>}
pullDownToRefresh
pullDownToRefreshThreshold={50}
refreshFunction={refreshList}
pullDownToRefreshContent={
<h3 style={{ textAlign: 'center' }}>↓ Pull down to refresh</h3>
}
releaseToRefreshContent={
<h3 style={{ textAlign: 'center' }}>↑ Release to refresh</h3>
}
>
{items.map((item) => (
<div key={item.id}>{item.name}</div>
))}
</InfiniteScroll>
useInfiniteScroll hookFor when you need full control over your markup. Place the sentinelRef div at the end of your list, the hook fires next() when it enters the viewport.
import { useState } from 'react';
import { useInfiniteScroll } from 'react-infinite-scroll-component';
type Item = { id: number; name: string };
function CustomFeed() {
const [items, setItems] = useState<Item[]>(initialItems);
const [hasMore, setHasMore] = useState(true);
const { sentinelRef, isLoading } = useInfiniteScroll({
next: async () => {
const more = await api.getItems({ offset: items.length });
if (more.length === 0) {
setHasMore(false);
return;
}
setItems((prev) => [...prev, ...more]);
},
hasMore,
dataLength: items.length,
});
return (
<ul>
{items.map((item) => (
<li key={item.id}>{item.name}</li>
))}
<li ref={sentinelRef} aria-hidden="true" />
{isLoading && <li>Loading...</li>}
{!hasMore && <li>All items loaded.</li>}
</ul>
);
}
InfiniteScroll is a client component. Fetch initial data in a Server Component, pass it down.
// app/feed/page.tsx, Server Component
import { FeedClient } from './feed-client';
import { db } from '@/lib/db';
export default async function FeedPage() {
const initialItems = await db.items.findMany({
take: 20,
orderBy: { id: 'desc' },
});
return <FeedClient initialItems={initialItems} />;
}
// app/feed/feed-client.tsx, Client Component
'use client';
import { useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
type Item = { id: string; title: string };
export function FeedClient({ initialItems }: { initialItems: Item[] }) {
const [items, setItems] = useState(initialItems);
const [hasMore, setHasMore] = useState(true);
const fetchMore = async () => {
const res = await fetch(`/api/items?cursor=${items[items.length - 1].id}`);
const next: Item[] = await res.json();
if (next.length === 0) {
setHasMore(false);
return;
}
setItems((prev) => [...prev, ...next]);
};
return (
<InfiniteScroll
dataLength={items.length}
next={fetchMore}
hasMore={hasMore}
loader={<p>Loading...</p>}
endMessage={<p>You have seen everything.</p>}
>
{items.map((item) => (
<article key={item.id}>{item.title}</article>
))}
</InfiniteScroll>
);
}
import { useInfiniteQuery } from '@tanstack/react-query';
import InfiniteScroll from 'react-infinite-scroll-component';
function PostFeed() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } =
useInfiniteQuery({
queryKey: ['posts'],
queryFn: ({ pageParam = 0 }) => fetchPosts(pageParam),
getNextPageParam: (lastPage, pages) =>
lastPage.length === 20 ? pages.length : undefined,
});
const posts = data?.pages.flat() ?? [];
return (
<InfiniteScroll
dataLength={posts.length}
next={fetchNextPage}
hasMore={!!hasNextPage}
loader={isFetchingNextPage ? <p>Loading...</p> : null}
endMessage={<p>All posts loaded.</p>}
>
{posts.map((post) => (
<article key={post.id}>{post.title}</article>
))}
</InfiniteScroll>
);
}
import useSWRInfinite from 'swr/infinite';
import InfiniteScroll from 'react-infinite-scroll-component';
const PAGE_SIZE = 20;
function PostList() {
const { data, size, setSize } = useSWRInfinite(
(index) => `/api/posts?page=${index}&limit=${PAGE_SIZE}`,
fetcher
);
const posts = data ? data.flat() : [];
const hasMore = data ? data[data.length - 1].length === PAGE_SIZE : true;
return (
<InfiniteScroll
dataLength={posts.length}
next={() => setSize(size + 1)}
hasMore={hasMore}
loader={<p>Loading...</p>}
>
{posts.map((post) => (
<div key={post.id}>{post.title}</div>
))}
</InfiniteScroll>
);
}
| Mode | How to use | Use case |
|---|---|---|
| Window scroll | Omit height and scrollableTarget | Social feeds, blogs, product listings |
| Fixed-height container | Pass height prop | Embedded lists, sidebars |
| Custom scrollable parent | Pass scrollableTarget (element or id) | Existing overflow containers |
InfiniteScroll| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
dataLength | number | yes | - | Current count of rendered items. The component resets its load guard each time this value changes, which allows next() to fire again on the next scroll. |
next | () => void | yes | - | Called once when the sentinel enters the viewport. Append new items to your list state inside this callback; do not replace the existing items. |
hasMore | boolean | yes | - | When false, the observer is disconnected and next() will not be called again. Set it to false when your data source has no more pages. |
loader | ReactNode | yes | - | Rendered below the list while the next page is loading. Displayed between the last item and the bottom sentinel. |
endMessage | ReactNode | no | - | Rendered below the list when hasMore is false. Use it for an "all caught up" or "no more items" message. |
height | number | string | no | - | Creates a fixed-height scroll container wrapping the list. Accepts a pixel number or any CSS length string. Omit this prop to scroll the window instead. |
scrollableTarget | HTMLElement | string | null | no | - | The scrollable ancestor that already provides overflow scrollbars. Pass the element's id string or a direct HTMLElement reference. Required when the scroll container is neither the window nor the height wrapper. |
scrollThreshold | number | string | no | 0.8 | How close to the bottom the user must scroll before next() is called. A fraction like 0.8 means 80% scrolled; a string like "200px" means within 200 px of the bottom edge. |
inverse | boolean | no | false | Reverse scroll direction for chat or messaging UIs. The sentinel moves to the top of the list. Use together with flexDirection: column-reverse on the scroll container. |
pullDownToRefresh | boolean | no | false | Enable pull-to-refresh gesture on touch and mouse. Requires refreshFunction to also be set. |
refreshFunction | () => void | no | - | Called once when the user pulls down past pullDownToRefreshThreshold pixels and releases. Only active when pullDownToRefresh is true. |
pullDownToRefreshThreshold | number | no | 100 | How many pixels the user must pull down before refreshFunction is triggered on release. |
pullDownToRefreshContent | ReactNode | no | - | Content shown inside the pull-to-refresh area while the user is pulling but has not yet reached the threshold. |
releaseToRefreshContent | ReactNode | no | - | Content shown inside the pull-to-refresh area once the threshold is passed and the user can release to refresh. |
onScroll | (e: UIEvent) => void | no | - | Callback fired on every scroll event on the container. Receives the native UIEvent. Useful for syncing UI state with scroll position. |
className | string | no | '' | CSS class name applied to the inner scroll container div. |
style | CSSProperties | no | - | Inline style object applied to the inner scroll container div. Merged with the component's default layout styles. |
role | AriaRole | no | - | Semantic role for the scroll container. Use "list" for item lists, "feed" for activity streams. |
tabIndex | number | no | - | Makes the scroll container focusable. Pass 0 to include it in the natural tab sequence. |
id | string | no | - | DOM id for the container. Useful when other elements reference it via aria-labelledby. |
aria-* | AriaAttributes | no | - | Any React aria-* prop (aria-label, aria-labelledby, aria-describedby, etc.) forwarded to the scroll container. |
hasChildren | boolean | no | - | Set to true when children is a single element or a fragment rather than an array. Helps the component detect whether visible content exists to determine scroll state. |
initialScrollY | number | no | - | Scrolls the window to this Y offset on mount. Useful for restoring a user's scroll position when navigating back to a page. |
Pass role and a label so screen readers can announce the container and its item count correctly:
<InfiniteScroll
role="list"
aria-label="Search results"
dataLength={items.length}
next={fetchMore}
hasMore={hasMore}
loader={<p>Loading...</p>}
>
{items.map((item) => (
<div role="listitem" key={item.id}>
{item.name}
</div>
))}
</InfiniteScroll>
Or reference an existing heading via aria-labelledby:
<h2 id="results-heading">Search results</h2>
<InfiniteScroll
role="list"
aria-labelledby="results-heading"
dataLength={items.length}
next={fetchMore}
hasMore={hasMore}
loader={<p>Loading...</p>}
>
useInfiniteScroll| Prop | Type | Required | Default | Description |
|---|---|---|---|---|
dataLength | number | yes | - | Current count of rendered items. The hook resets its load guard whenever this value changes, allowing next() to fire again on the next intersection. |
next | () => void | yes | - | Called once when the sentinel enters the viewport. Append new items to your list state inside this callback; do not replace the existing items. |
hasMore | boolean | yes | - | When false, the IntersectionObserver is disconnected and next() will not be called again. Set it to false when your data source has no more pages. |
scrollThreshold | number | string | no | 0.8 | How close to the edge the sentinel must be before next() fires. A fraction like 0.8 means 80% scrolled; a string like "200px" means within 200 px of the edge. |
scrollableTarget | HTMLElement | string | null | no | - | The scrollable ancestor to use as the observer root. Pass a DOM id string or an HTMLElement reference. When omitted, the observer uses the browser viewport. |
inverse | boolean | no | false | When true, the rootMargin is applied to the top edge instead of the bottom. Place the sentinel at the top of your list and use flexDirection: column-reverse for chat UIs. |
Returns { sentinelRef, isLoading }.
next() fires once when the sentinel enters the viewport, not on every scroll tick. No missed triggers, better performance.useInfiniteScroll hook, low-level hook for building fully custom UIs.throttle-debounce removed.scrollableTarget accepts HTMLElement, pass a ref value directly, not just a string id.scrollableTarget
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind are welcome!