react-infinite-scroll-component vs react-infinite-scroll-component
無限スクロール実装のためのReactコンポーネント比較
react-infinite-scroll-componentreact-infinite-scroll-component
無限スクロール実装のためのReactコンポーネント比較

react-infinite-scroll-component は、Reactアプリケーションで無限スクロール(インフィニットスクロール)機能を簡単に実装するための軽量なコンポーネントです。指定した要素がビューポート内に近づいたときにコールバックを呼び出すことで、新しいコンテンツを動的に読み込む仕組みを提供します。このパッケージは、リストやグリッドなどの縦方向スクロール領域での遅延読み込みに特化しており、ローディングインジケーターや終了状態の表示もサポートしています。

npmのダウンロードトレンド
3 年
GitHub Starsランキング
統計詳細
パッケージ
ダウンロード数
Stars
サイズ
Issues
公開日時
ライセンス
react-infinite-scroll-component898,9863,046169 kB1982日前MIT
react-infinite-scroll-component898,9863,046169 kB1982日前MIT

react-infinite-scroll-component の技術的評価

指定された2つのパッケージ名は完全に同一(react-infinite-scroll-component)であり、実際には1つのnpmパッケージを指しています。このため、通常の「比較」ではなく、そのパッケージの技術的特性と使用上の考慮点を深掘りします。

📦 パッケージの正体と現状

react-infinite-scroll-component は、Ankeet Maini氏によって開発・公開されている無限スクロール用Reactコンポーネントです。公式npmページおよびGitHubリポジトリを確認したところ、非推奨(deprecated)ではないものの、最新のメジャーバージョン(v6以降)ではメンテナンス頻度が低下している傾向があります。ただし、基本的な機能は安定しており、多くのプロダクション環境で利用されています。

⚠️ 注意:この比較では、同一パッケージが2つ指定されているため、代替選択肢としての比較は行えません。実際のプロジェクトでは、react-intersection-observer@tanem/react-infinite-scroller など他の選択肢も検討すべきです。

🧩 基本的な使い方とAPI設計

このコンポーネントは、非常にシンプルなProps APIを提供します。主なプロパティは以下の通りです:

  • dataLength: 現在読み込まれているアイテムの総数
  • next: 次のページを読み込む関数
  • hasMore: さらに読み込むデータがあるかどうか
  • loader: 読み込み中の表示要素
  • endMessage: 全てのデータを読み込んだ後のメッセージ
import InfiniteScroll from 'react-infinite-scroll-component';

function MyList({ items, loadMore, hasMore }) {
  return (
    <InfiniteScroll
      dataLength={items.length}
      next={loadMore}
      hasMore={hasMore}
      loader={<div>Loading...</div>}
      endMessage={<p>これ以上ありません</p>}
    >
      {items.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </InfiniteScroll>
  );
}

🔍 内部動作とパフォーマンス特性

このコンポーネントは、内部で scroll イベントと getBoundingClientRect() を使用して、スクロール位置が閾値に達したかを判定します。デフォルトでは、コンテナの下端から 約150px 手前で next コールバックを呼び出します。

重要なのは、スクロールイベントが高頻度で発火するため、内部でthrottle処理が行われていない点です。大量のアイテムをレンダリングする場合、スクロール時のパフォーマンスに影響が出る可能性があります。また、モバイルデバイスではスクロールイベントのタイミングが不安定になることもあり、読み込みが遅れるケースがあります。

🛠️ カスタマイズ性と制限

閾値の調整

読み込み開始位置は scrollThreshold propで調整可能です:

<InfiniteScroll
  scrollThreshold="200px" // または 0.8(ビューポートの80%)
  // ...
/>

スクロール対象の指定

デフォルトではウィンドウ全体のスクロールを監視しますが、特定の要素内でのスクロールを監視することもできます:

<div id="scrollableDiv" style={{ height: '400px', overflow: 'auto' }}>
  <InfiniteScroll
    scrollableTarget="scrollableDiv"
    // ...
  >
    {/* コンテンツ */}
  </InfiniteScroll>
</div>

制限事項

  • 水平スクロールには非対応:縦方向スクロール専用です。
  • 仮想化との併用が難しいreact-windowreact-virtualized と組み合わせる場合、スクロール監視の競合が発生することがあります。
  • 初期読み込み時の挙動に注意dataLength が0の場合、最初の next 呼び出しが自動で行われないため、マウント時に手動で1回読み込む必要があります。

💡 実践的な使用例とベストプラクティス

初期データの読み込み

function UserFeed() {
  const [items, setItems] = useState([]);
  const [hasMore, setHasMore] = useState(true);

  const fetchMoreData = async () => {
    const newItems = await api.fetchPage(items.length / 10 + 1);
    setItems(prev => [...prev, ...newItems]);
    if (newItems.length === 0) setHasMore(false);
  };

  // 初期読み込み
  useEffect(() => {
    fetchMoreData();
  }, []);

  return (
    <InfiniteScroll
      dataLength={items.length}
      next={fetchMoreData}
      hasMore={hasMore}
      loader={<Spinner />}
    >
      {items.map(item => <UserCard key={item.id} user={item} />)}
    </InfiniteScroll>
  );
}

エラーハンドリングの追加

このコンポーネント自体はエラーハンドリングを提供しません。そのため、以下のようにラップして再試行UIを実装するのが一般的です:

function SafeInfiniteScroll({ children, onLoadError, ...props }) {
  const [error, setError] = useState(null);

  const safeNext = async () => {
    try {
      await props.next();
      setError(null);
    } catch (err) {
      setError(err);
      onLoadError?.(err);
    }
  };

  return (
    <>
      <InfiniteScroll {...props} next={safeNext}>
        {children}
      </InfiniteScroll>
      {error && (
        <button onClick={safeNext}>再試行</button>
      )}
    </>
  );
}

🆚 同様の要件に対する代替アプローチ

react-infinite-scroll-component が唯一の選択肢ではないことを認識することが重要です:

Intersection Observer API を直接使う

より細かい制御が必要な場合は、ブラウザ標準のIntersection Observerを直接使う方法があります:

function useInfiniteScroll(callback, deps = []) {
  const sentinelRef = useRef(null);

  useEffect(() => {
    const observer = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting) callback();
    });

    if (sentinelRef.current) observer.observe(sentinelRef.current);
    return () => observer.disconnect();
  }, [callback, ...deps]);

  return sentinelRef;
}

// 使用例
function MyList() {
  const sentinelRef = useInfiniteScroll(loadMore);
  return (
    <>
      {items.map(item => <div key={item.id}>{item.name}</div>)}
      <div ref={sentinelRef} />
    </>
  );
}

この方法は依存関係を減らし、パフォーマンスを向上させますが、ローディング状態やエラーハンドリングはすべて自分で実装する必要があります。

📌 まとめ:いつ使うべきか

react-infinite-scroll-component は以下のようなケースで有効です:

  • 短期間で無限スクロールを実装したい:数行のコードで機能を追加可能
  • 複雑なカスタマイズが不要:標準的な縦スクロールリストに十分対応
  • 軽量さを重視:バンドルサイズが小さく、依存関係が少ない

一方で、以下のような要件がある場合は代替手段を検討すべきです:

  • 高性能な仮想化リストが必要react-window + カスタム無限スクロールロジック
  • 水平スクロールやグリッド対応が必要react-intersection-observer を活用
  • 細かいパフォーマンスチューニングが必要 → Intersection Observerを直接使用

最終的には、プロジェクトの規模・要件・メンテナンスコストを総合的に判断し、最適なアプローチを選んでください。

選び方: react-infinite-scroll-component vs react-infinite-scroll-component
  • react-infinite-scroll-component:

    react-infinite-scroll-component はシンプルな無限スクロールを必要とするプロジェクトに適しています。特に、既存のUIに最小限の変更で無限読み込み機能を追加したい場合や、複雑なカスタマイズを必要としないケースで効果的です。ただし、同一パッケージ名が重複して指定されているため、実際には1つの選択肢しか存在しません。

  • react-infinite-scroll-component:

    react-infinite-scroll-component はシンプルな無限スクロールを必要とするプロジェクトに適しています。特に、既存のUIに最小限の変更で無限読み込み機能を追加したい場合や、複雑なカスタマイズを必要としないケースで効果的です。ただし、同一パッケージ名が重複して指定されているため、実際には1つの選択肢しか存在しません。

react-infinite-scroll-component のREADME

react-infinite-scroll-component npm npm

All Contributors

A component to make all your infinite scrolling woes go away with just 4.15 kB! Pull Down to Refresh feature added. An infinite-scroll that actually works and super-simple to integrate!

Install

  npm install --save react-infinite-scroll-component

  or

  yarn add react-infinite-scroll-component

  // in code ES6
  import InfiniteScroll from 'react-infinite-scroll-component';
  // or commonjs
  var InfiniteScroll = require('react-infinite-scroll-component');

Using

<InfiniteScroll
  dataLength={items.length} //This is important field to render the next data
  next={fetchData}
  hasMore={true}
  loader={<h4>Loading...</h4>}
  endMessage={
    <p style={{ textAlign: 'center' }}>
      <b>Yay! You have seen it all</b>
    </p>
  }
  // below props only if you need pull down functionality
  refreshFunction={this.refresh}
  pullDownToRefresh
  pullDownToRefreshThreshold={50}
  pullDownToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8595; Pull down to refresh</h3>
  }
  releaseToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8593; Release to refresh</h3>
  }
>
  {items}
</InfiniteScroll>

Using scroll on top

<div
  id="scrollableDiv"
  style={{
    height: 300,
    overflow: 'auto',
    display: 'flex',
    flexDirection: 'column-reverse',
  }}
>
  {/*Put the scroll bar always on the bottom*/}
  <InfiniteScroll
    dataLength={this.state.items.length}
    next={this.fetchMoreData}
    style={{ display: 'flex', flexDirection: 'column-reverse' }} //To put endMessage and loader to the top.
    inverse={true} //
    hasMore={true}
    loader={<h4>Loading...</h4>}
    scrollableTarget="scrollableDiv"
  >
    {this.state.items.map((_, index) => (
      <div style={style} key={index}>
        div - #{index}
      </div>
    ))}
  </InfiniteScroll>
</div>

The InfiniteScroll component can be used in three ways.

  • Specify a value for the height prop if you want your scrollable content to have a specific height, providing scrollbars for scrolling your content and fetching more data.
  • If your scrollable content is being rendered within a parent element that is already providing overflow scrollbars, you can set the scrollableTarget prop to reference the DOM element and use it's scrollbars for fetching more data.
  • Without setting either the height or scrollableTarget props, the scroll will happen at document.body like Facebook's timeline scroll.

docs version wise

3.0.2

live examples

  • infinite scroll (never ending) example using react (body/window scroll)
    • Edit yk7637p62z
  • infinte scroll till 500 elements (body/window scroll)
    • Edit 439v8rmqm0
  • infinite scroll in an element (div of height 400px)
    • Edit w3w89k7x8
  • infinite scroll with scrollableTarget (a parent element which is scrollable)
    • Edit r7rp40n0zm

props

nametypedescription
nextfunctiona function which must be called after reaching the bottom. It must trigger some sort of action which fetches the next data. The data is passed as children to the InfiniteScroll component and the data should contain previous items too. e.g. Initial data = [1, 2, 3] and then next load of data should be [1, 2, 3, 4, 5, 6].
hasMorebooleanit tells the InfiniteScroll component on whether to call next function on reaching the bottom and shows an endMessage to the user
childrennode (list)the data items which you need to scroll.
dataLengthnumberset the length of the data.This will unlock the subsequent calls to next.
loadernodeyou can send a loader component to show while the component waits for the next load of data. e.g. <h3>Loading...</h3> or any fancy loader element
scrollThresholdnumber | stringA threshold value defining when InfiniteScroll will call next. Default value is 0.8. It means the next will be called when user comes below 80% of the total height. If you pass threshold in pixels (scrollThreshold="200px"), next will be called once you scroll at least (100% - scrollThreshold) pixels down.
onScrollfunctiona function that will listen to the scroll event on the scrolling container. Note that the scroll event is throttled, so you may not receive as many events as you would expect.
endMessagenodethis message is shown to the user when he has seen all the records which means he's at the bottom and hasMore is false
classNamestringadd any custom class you want
styleobjectany style which you want to override
heightnumberoptional, give only if you want to have a fixed height scrolling content
scrollableTargetnode or stringoptional, reference to a (parent) DOM element that is already providing overflow scrollbars to the InfiniteScroll component. You should provide the id of the DOM node preferably.
hasChildrenboolchildren is by default assumed to be of type array and it's length is used to determine if loader needs to be shown or not, if your children is not an array, specify this prop to tell if your items are 0 or more.
pullDownToRefreshboolto enable Pull Down to Refresh feature
pullDownToRefreshContentnodeany JSX that you want to show the user, default={<h3>Pull down to refresh</h3>}
releaseToRefreshContentnodeany JSX that you want to show the user, default={<h3>Release to refresh</h3>}
pullDownToRefreshThresholdnumberminimum distance the user needs to pull down to trigger the refresh, default=100px , a lower value may be needed to trigger the refresh depending your users browser.
refreshFunctionfunctionthis function will be called, it should return the fresh data that you want to show the user
initialScrollYnumberset a scroll y position for the component to render with.
inverseboolset infinite scroll on top

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Ankeet Maini

💬 📖 💻 👀 🚧

Darsh Shah

🚇

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

LICENSE

MIT

react-infinite-scroll-component のREADME

react-infinite-scroll-component npm npm

All Contributors

A component to make all your infinite scrolling woes go away with just 4.15 kB! Pull Down to Refresh feature added. An infinite-scroll that actually works and super-simple to integrate!

Install

  npm install --save react-infinite-scroll-component

  or

  yarn add react-infinite-scroll-component

  // in code ES6
  import InfiniteScroll from 'react-infinite-scroll-component';
  // or commonjs
  var InfiniteScroll = require('react-infinite-scroll-component');

Using

<InfiniteScroll
  dataLength={items.length} //This is important field to render the next data
  next={fetchData}
  hasMore={true}
  loader={<h4>Loading...</h4>}
  endMessage={
    <p style={{ textAlign: 'center' }}>
      <b>Yay! You have seen it all</b>
    </p>
  }
  // below props only if you need pull down functionality
  refreshFunction={this.refresh}
  pullDownToRefresh
  pullDownToRefreshThreshold={50}
  pullDownToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8595; Pull down to refresh</h3>
  }
  releaseToRefreshContent={
    <h3 style={{ textAlign: 'center' }}>&#8593; Release to refresh</h3>
  }
>
  {items}
</InfiniteScroll>

Using scroll on top

<div
  id="scrollableDiv"
  style={{
    height: 300,
    overflow: 'auto',
    display: 'flex',
    flexDirection: 'column-reverse',
  }}
>
  {/*Put the scroll bar always on the bottom*/}
  <InfiniteScroll
    dataLength={this.state.items.length}
    next={this.fetchMoreData}
    style={{ display: 'flex', flexDirection: 'column-reverse' }} //To put endMessage and loader to the top.
    inverse={true} //
    hasMore={true}
    loader={<h4>Loading...</h4>}
    scrollableTarget="scrollableDiv"
  >
    {this.state.items.map((_, index) => (
      <div style={style} key={index}>
        div - #{index}
      </div>
    ))}
  </InfiniteScroll>
</div>

The InfiniteScroll component can be used in three ways.

  • Specify a value for the height prop if you want your scrollable content to have a specific height, providing scrollbars for scrolling your content and fetching more data.
  • If your scrollable content is being rendered within a parent element that is already providing overflow scrollbars, you can set the scrollableTarget prop to reference the DOM element and use it's scrollbars for fetching more data.
  • Without setting either the height or scrollableTarget props, the scroll will happen at document.body like Facebook's timeline scroll.

docs version wise

3.0.2

live examples

  • infinite scroll (never ending) example using react (body/window scroll)
    • Edit yk7637p62z
  • infinte scroll till 500 elements (body/window scroll)
    • Edit 439v8rmqm0
  • infinite scroll in an element (div of height 400px)
    • Edit w3w89k7x8
  • infinite scroll with scrollableTarget (a parent element which is scrollable)
    • Edit r7rp40n0zm

props

nametypedescription
nextfunctiona function which must be called after reaching the bottom. It must trigger some sort of action which fetches the next data. The data is passed as children to the InfiniteScroll component and the data should contain previous items too. e.g. Initial data = [1, 2, 3] and then next load of data should be [1, 2, 3, 4, 5, 6].
hasMorebooleanit tells the InfiniteScroll component on whether to call next function on reaching the bottom and shows an endMessage to the user
childrennode (list)the data items which you need to scroll.
dataLengthnumberset the length of the data.This will unlock the subsequent calls to next.
loadernodeyou can send a loader component to show while the component waits for the next load of data. e.g. <h3>Loading...</h3> or any fancy loader element
scrollThresholdnumber | stringA threshold value defining when InfiniteScroll will call next. Default value is 0.8. It means the next will be called when user comes below 80% of the total height. If you pass threshold in pixels (scrollThreshold="200px"), next will be called once you scroll at least (100% - scrollThreshold) pixels down.
onScrollfunctiona function that will listen to the scroll event on the scrolling container. Note that the scroll event is throttled, so you may not receive as many events as you would expect.
endMessagenodethis message is shown to the user when he has seen all the records which means he's at the bottom and hasMore is false
classNamestringadd any custom class you want
styleobjectany style which you want to override
heightnumberoptional, give only if you want to have a fixed height scrolling content
scrollableTargetnode or stringoptional, reference to a (parent) DOM element that is already providing overflow scrollbars to the InfiniteScroll component. You should provide the id of the DOM node preferably.
hasChildrenboolchildren is by default assumed to be of type array and it's length is used to determine if loader needs to be shown or not, if your children is not an array, specify this prop to tell if your items are 0 or more.
pullDownToRefreshboolto enable Pull Down to Refresh feature
pullDownToRefreshContentnodeany JSX that you want to show the user, default={<h3>Pull down to refresh</h3>}
releaseToRefreshContentnodeany JSX that you want to show the user, default={<h3>Release to refresh</h3>}
pullDownToRefreshThresholdnumberminimum distance the user needs to pull down to trigger the refresh, default=100px , a lower value may be needed to trigger the refresh depending your users browser.
refreshFunctionfunctionthis function will be called, it should return the fresh data that you want to show the user
initialScrollYnumberset a scroll y position for the component to render with.
inverseboolset infinite scroll on top

Contributors ✨

Thanks goes to these wonderful people (emoji key):


Ankeet Maini

💬 📖 💻 👀 🚧

Darsh Shah

🚇

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

LICENSE

MIT