react-infinite-scroll-component vs react-window-infinite-loader vs react-infinite-scroller
React 無限スクロール実装の技術比較
react-infinite-scroll-componentreact-window-infinite-loaderreact-infinite-scroller類似套件:

React 無限スクロール実装の技術比較

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 と連携して仮想化による高性能を実現します。

npm下載趨勢

3 年

GitHub Stars 排名

統計詳情

套件
下載數
Stars
大小
Issues
發布時間
許可
react-infinite-scroll-component1,831,4423,090217 kB1385 個月前MIT
react-window-infinite-loader1,067,42295026.3 kB010 天前MIT
react-infinite-scroller604,6603,29230.3 kB98-MIT

React 無限スクロールライブラリ:性能、実装、アーキテクチャ比較

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 も同様に全アイテムをレンダリングします。

  • 依存関係が軽量
  • window スクロールと要素スクロールの両方をサポート
  • 大規模データには非推奨
// 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 で現在のアイテム数を通知
  • 状態管理の責任は開発者に委ねられる
  • Redux や Context との統合が容易
// 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 で現在のページを追跡
  • 古い API 設計(クラスコンポーネント時代の名残り)
// 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 のパフォーマンス特性:

  • 1000 件程度までは問題なく動作
  • 5000 件を超えるとスクロールが重くなる可能性
  • メモリ使用量がデータ量に比例して増加
  • シンプルな実装のためオーバーヘッドが少ない
// 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 のパフォーマンス特性:

  • 表示中のアイテム(通常 20〜50 件)のみをレンダリング
  • 10 万件以上のデータでもスムーズに動作
  • メモリ使用量が一定に保たれる
  • 初期設定のオーバーヘッドがある
// 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 はスクロール位置の保持が容易です。

  • 標準的な DOM 要素として動作
  • 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>
  );
}

🎨 UI カスタマイズ:ローダーとエンド表示

ローディング状態や終了時の表示も重要な 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 ライブラリの共有機能

これらのライブラリには多くの共通点もあります。

1. ⚛️ React コンポーネントとして実装

  • すべて関数コンポーネントまたはクラスコンポーネントとして使用可能
  • React のライフサイクルと統合
  • Hooks との併用が可能
// 3 ライブラリ共通:React コンポーネントとして使用
function UserList({ users, fetchMore, hasMore }) {
  // どのライブラリでも同様のパターンで使用可能
  return (
    <InfiniteScrollComponent
      // 各ライブラリの props を設定
    >
      {users.map(user => <UserCard key={user.id} user={user} />)}
    </InfiniteScrollComponent>
  );
}

2. 📱 両方向スクロールサポート

  • window スクロールと要素スクロールの両方をサポート
  • useWindow または scrollableTarget で制御
  • モバイルデバイスでも動作
// window スクロールの場合
<InfiniteScroll useWindow={true}>
  {/* 内容 */}
</InfiniteScroll>

// 要素スクロールの場合
<div style={{ height: '600px', overflow: 'auto' }}>
  <InfiniteScroll useWindow={false}>
    {/* 内容 */}
  </InfiniteScroll>
</div>

3. 🔄 非同期データ読み込み

  • next、loadMore、loadMoreItems でデータ取得をトリガー
  • Promise ベースの非同期処理をサポート
  • エラーハンドリングは開発者側で実装
// 3 ライブラリ共通:非同期データ読み込みパターン
const fetchMore = async () => {
  try {
    const newItems = await api.getData(page);
    setItems([...items, ...newItems]);
  } catch (error) {
    console.error('データ取得エラー:', error);
    // エラー状態の管理は開発者側で
  }
};

4. ✅ TypeScript サポート

  • すべて TypeScript 定義ファイルを提供
  • 型安全性を確保可能
  • IDE での補完が利用可能
// TypeScript での使用例(3 ライブラリ共通)
interface User {
  id: number;
  name: string;
}

interface Props {
  users: User[];
  fetchMore: () => Promise<void>;
  hasMore: boolean;
}

function UserList({ users, fetchMore, hasMore }: Props) {
  // 型チェックが機能
}

5. 🎯 スクロールトリガー閾値

  • スクロール位置の閾値を設定可能
  • 早期にデータを読み込むことで UX を向上
  • scrollThreshold props で制御
// スクロール閾値の設定(対応ライブラリ)
<InfiniteScroll
  scrollThreshold={0.8} // 80% スクロールでトリガー
  // 早期読み込みでユーザー待機時間を削減
>
  {/* 内容 */}
</InfiniteScroll>

📊 比較サマリー表

機能react-infinite-scroll-componentreact-infinite-scrollerreact-window-infinite-loader
仮想化❌ 全アイテムレンダリング❌ 全アイテムレンダリング✅ 表示中のみのレンダリング
最大推奨アイテム数~1000 件~1000 件10 万件以上
メモリ使用量データ量に比例データ量に比例一定
実装の複雑さ低低中〜高
スクロール位置保持容易容易特殊な制御が必要
メンテナンス状況活発要注意活発
依存関係軽量軽量react-window が必要

💡 最終推奨

データ量とパフォーマンス要件で選択しましょう:

  • 1000 件未満のリスト → react-infinite-scroll-component(シンプルで十分)
  • 既存プロジェクトの維持 → react-infinite-scroller(変更コストを考慮)
  • 1000 件以上の大規模データ → react-window-infinite-loader(性能が最優先)
  • エンタープライズアプリケーション → react-window-infinite-loader(安定性と拡張性)

重要なポイント:無限スクロール実装では、初期の開発速度よりも長期的なパフォーマンスとメンテナンス性を重視すべきです。プロジェクトの規模と成長を見据えて、適切なライブラリを選択しましょう。

如何選擇: react-infinite-scroll-component vs react-window-infinite-loader vs react-infinite-scroller

  • react-infinite-scroll-component:

    react-infinite-scroll-component を選択するのは、シンプルな実装で十分な場合や、仮想化の複雑さを避けたいプロジェクトです。メンテナンスが活発で API が直感的ですが、大量のデータ(1000 件以上)をレンダリングするとパフォーマンスが低下する可能性があります。小〜中規模のリストや、プロトタイプ開発に適しています。

  • react-window-infinite-loader:

    react-window-infinite-loader を選択するのは、大規模なデータセット(数千件以上)を扱う場合や、パフォーマンスが最優先事項の場合です。react-window と連携して仮想化を実現し、表示されているアイテムのみをレンダリングするため、メモリ使用量と描画コストを大幅に削減できます。エンタープライズアプリケーションやデータ密集型プロジェクトに最適です。

  • react-infinite-scroller:

    react-infinite-scroller を選択するのは、軽量な依存関係とシンプルな API を優先する場合です。ただし、メンテナンス状況に注意が必要で、新しいプロジェクトでは慎重に評価すべきです。既存プロジェクトの維持や、仮想化が不要なシンプルなユースケースに適しています。

react-infinite-scroll-component 的 README

react-infinite-scroll-component npm npm bundlephobia

All Contributors

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.

Install

npm install react-infinite-scroll-component
# or
yarn add react-infinite-scroll-component
# or
pnpm add react-infinite-scroll-component

Two APIs

APIWhen to use
InfiniteScroll componentMost cases, handles loader, endMessage, pull-to-refresh, inverse scroll UI
useInfiniteScroll hookCustom UI, you own the markup, the hook manages the observer

InfiniteScroll component

Basic usage (TypeScript)

import { 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>
  );
}

Scroll inside a fixed-height container

<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>;

Inverse scroll (chat / messaging UIs)

<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>

Pull-to-refresh

<InfiniteScroll
  dataLength={items.length}
  next={fetchMore}
  hasMore={hasMore}
  loader={<p>Loading...</p>}
  pullDownToRefresh
  pullDownToRefreshThreshold={50}
  refreshFunction={refreshList}
  pullDownToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8595; Pull down to refresh</h3>
  }
  releaseToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8593; Release to refresh</h3>
  }
>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</InfiniteScroll>

useInfiniteScroll hook

For 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>
  );
}

Framework recipes

Next.js App Router

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>
  );
}

With TanStack Query

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>
  );
}

With SWR

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>
  );
}

Three scroll modes

ModeHow to useUse case
Window scrollOmit height and scrollableTargetSocial feeds, blogs, product listings
Fixed-height containerPass height propEmbedded lists, sidebars
Custom scrollable parentPass scrollableTarget (element or id)Existing overflow containers

Props, InfiniteScroll

PropTypeRequiredDefaultDescription
dataLengthnumberyes-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() => voidyes-Called once when the sentinel enters the viewport. Append new items to your list state inside this callback; do not replace the existing items.
hasMorebooleanyes-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.
loaderReactNodeyes-Rendered below the list while the next page is loading. Displayed between the last item and the bottom sentinel.
endMessageReactNodeno-Rendered below the list when hasMore is false. Use it for an "all caught up" or "no more items" message.
heightnumber | stringno-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.
scrollableTargetHTMLElement | string | nullno-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.
scrollThresholdnumber | stringno0.8How 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.
inversebooleannofalseReverse 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.
pullDownToRefreshbooleannofalseEnable pull-to-refresh gesture on touch and mouse. Requires refreshFunction to also be set.
refreshFunction() => voidno-Called once when the user pulls down past pullDownToRefreshThreshold pixels and releases. Only active when pullDownToRefresh is true.
pullDownToRefreshThresholdnumberno100How many pixels the user must pull down before refreshFunction is triggered on release.
pullDownToRefreshContentReactNodeno-Content shown inside the pull-to-refresh area while the user is pulling but has not yet reached the threshold.
releaseToRefreshContentReactNodeno-Content shown inside the pull-to-refresh area once the threshold is passed and the user can release to refresh.
onScroll(e: UIEvent) => voidno-Callback fired on every scroll event on the container. Receives the native UIEvent. Useful for syncing UI state with scroll position.
classNamestringno''CSS class name applied to the inner scroll container div.
styleCSSPropertiesno-Inline style object applied to the inner scroll container div. Merged with the component's default layout styles.
roleAriaRoleno-Semantic role for the scroll container. Use "list" for item lists, "feed" for activity streams.
tabIndexnumberno-Makes the scroll container focusable. Pass 0 to include it in the natural tab sequence.
idstringno-DOM id for the container. Useful when other elements reference it via aria-labelledby.
aria-*AriaAttributesno-Any React aria-* prop (aria-label, aria-labelledby, aria-describedby, etc.) forwarded to the scroll container.
hasChildrenbooleanno-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.
initialScrollYnumberno-Scrolls the window to this Y offset on mount. Useful for restoring a user's scroll position when navigating back to a page.

Accessibility

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>}
>

Props, useInfiniteScroll

PropTypeRequiredDefaultDescription
dataLengthnumberyes-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() => voidyes-Called once when the sentinel enters the viewport. Append new items to your list state inside this callback; do not replace the existing items.
hasMorebooleanyes-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.
scrollThresholdnumber | stringno0.8How 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.
scrollableTargetHTMLElement | string | nullno-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.
inversebooleannofalseWhen 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 }.


What's new in v7

  • IntersectionObserver-based triggering, 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.
  • Zero runtime dependencies, throttle-debounce removed.
  • scrollableTarget accepts HTMLElement, pass a ref value directly, not just a string id.
  • Function component rewrite, same public API, no migration needed.
  • React 17, 18, 19 compatible.

live examples

  • infinite scroll (never ending), window scroll
    • Edit yk7637p62z
  • infinite scroll till 500 elements, window scroll
    • Edit 439v8rmqm0
  • infinite scroll in an element (height 400px)
    • Edit w3w89k7x8
  • infinite scroll with scrollableTarget
    • Edit r7rp40n0zm

Contributors ✨

Thanks goes to these wonderful people (emoji key):

Ankeet Maini
Ankeet Maini

💬 📖 💻 👀 🚧
Darsh Shah
Darsh Shah

🚇 💻 👀 🚧
Eliya Cohen
Eliya Cohen

💻
Nitin Kukreja
Nitin Kukreja

💻
Bruno Sabetta
Bruno Sabetta

💻 📖
Osmar Pérez Bautista
Osmar Pérez Bautista

💻
Shreya Dahal
Shreya Dahal

💻
Vlad Harahan
Vlad Harahan

💻 📖
Daniel Caldas
Daniel Caldas

💻
Alaeddine Douagi
Alaeddine Douagi

💻
Carlos
Carlos

💻
Championrunner
Championrunner

📖
Daniel Sogl
Daniel Sogl

💻
Darren Oster
Darren Oster

💻
Illia Panasenko
Illia Panasenko

💻
Kiko Beats
Kiko Beats

💻
Matt Trussler
Matt Trussler

💻
Nimit Suwannagate
Nimit Suwannagate

💻
Rajat
Rajat

💻
Rich
Rich

💻
Ritesh Goyal
Ritesh Goyal

💻
babycannotsay
babycannotsay

💻
cesco
cesco

💻
Harry
Harry

💻
ludwig404
ludwig404

💻
Karl Johansson
Karl Johansson

💻
Geoffrey Teng
Geoffrey Teng

💻
Sayed Risat
Sayed Risat

💻 📖

This project follows the all-contributors specification. Contributions of any kind are welcome!

LICENSE

MIT