react-infinite-scroll-component vs react-window-infinite-loader vs react-infinite-scroller
Bibliotecas de Rolagem Infinita em React
react-infinite-scroll-componentreact-window-infinite-loaderreact-infinite-scrollerPacotes similares:

Bibliotecas de Rolagem Infinita em React

As bibliotecas de rolagem infinita em React são projetadas para facilitar a implementação de listas longas que carregam mais itens conforme o usuário rola para baixo. Elas ajudam a melhorar a experiência do usuário ao evitar o carregamento de todos os dados de uma vez, permitindo que os dados sejam carregados sob demanda, conforme necessário. Isso é especialmente útil em aplicações que lidam com grandes volumes de dados, como feeds de redes sociais ou listas de produtos.

Tendência de downloads npm

3 Anos

Ranking de GitHub Stars

Detalhe de estatísticas

Pacote
Downloads
Stars
Tamanho
Issues
Publicado em
Licença
react-infinite-scroll-component1,831,4423,090217 kB138il y a 5 moisMIT
react-window-infinite-loader1,067,42295026.3 kB0il y a 10 joursMIT
react-infinite-scroller604,6603,29230.3 kB98-MIT

Comparação de funcionalidades: react-infinite-scroll-component vs react-window-infinite-loader vs react-infinite-scroller

Facilidade de Uso

  • react-infinite-scroll-component:

    O react-infinite-scroll-component é conhecido por sua simplicidade e facilidade de uso. A configuração inicial é rápida, permitindo que os desenvolvedores implementem a rolagem infinita com apenas algumas linhas de código. A documentação é clara e fornece exemplos práticos, facilitando a adoção por novos usuários.

  • react-window-infinite-loader:

    O react-window-infinite-loader é mais complexo devido à sua combinação de virtualização e rolagem infinita. Embora a curva de aprendizado possa ser um pouco mais acentuada, ele é extremamente poderoso para listas grandes, exigindo que os desenvolvedores compreendam conceitos de virtualização para tirar o máximo proveito.

  • react-infinite-scroller:

    O react-infinite-scroller oferece uma API um pouco mais complexa, mas ainda assim acessível. Ele permite que os desenvolvedores definam callbacks para eventos de rolagem, o que pode exigir um pouco mais de configuração, mas oferece maior controle sobre o comportamento da rolagem infinita.

Desempenho

  • react-infinite-scroll-component:

    O desempenho do react-infinite-scroll-component é adequado para a maioria das aplicações, mas não possui otimizações avançadas para listas extremamente longas. Ele carrega novos itens conforme o usuário rola, mas pode não ser o mais eficiente em termos de renderização.

  • react-window-infinite-loader:

    O react-window-infinite-loader é projetado para desempenho máximo, utilizando virtualização para renderizar apenas os itens visíveis na tela. Isso reduz significativamente o tempo de renderização e melhora a experiência do usuário em listas muito grandes.

  • react-infinite-scroller:

    O react-infinite-scroller é mais eficiente em termos de desempenho, pois permite que os desenvolvedores controlem melhor o carregamento de dados e a renderização. Isso pode resultar em uma experiência de usuário mais suave, especialmente em listas com muitos itens.

Flexibilidade

  • react-infinite-scroll-component:

    Embora o react-infinite-scroll-component seja flexível, ele é mais adequado para casos de uso simples. Ele não oferece muitas opções de personalização, o que pode ser uma limitação para aplicações que exigem comportamentos mais complexos.

  • react-window-infinite-loader:

    O react-window-infinite-loader é o mais flexível dos três, permitindo a combinação de virtualização e rolagem infinita. Isso permite que os desenvolvedores criem soluções altamente personalizadas para listas grandes, mas requer um entendimento mais profundo de como a virtualização funciona.

  • react-infinite-scroller:

    O react-infinite-scroller é altamente flexível, permitindo que os desenvolvedores personalizem o comportamento da rolagem e integrem facilmente com outras bibliotecas ou soluções de gerenciamento de estado. Isso o torna uma boa escolha para aplicações que precisam de um controle mais granular.

Suporte a Eventos

  • react-infinite-scroll-component:

    O react-infinite-scroll-component oferece suporte básico a eventos de rolagem, permitindo que os desenvolvedores definam quando novos itens devem ser carregados. No entanto, a personalização é limitada em comparação com outras bibliotecas.

  • react-window-infinite-loader:

    O react-window-infinite-loader também suporta eventos de rolagem, mas sua verdadeira força está na combinação de virtualização e rolagem infinita, permitindo que os desenvolvedores gerenciem eventos de forma eficiente enquanto mantêm o desempenho.

  • react-infinite-scroller:

    O react-infinite-scroller fornece suporte robusto a eventos de rolagem, permitindo que os desenvolvedores definam callbacks para eventos de rolagem e personalizem o comportamento de carregamento de dados de acordo com suas necessidades específicas.

Documentação e Comunidade

  • react-infinite-scroll-component:

    A documentação do react-infinite-scroll-component é clara e acessível, com exemplos práticos que facilitam a implementação. A comunidade é ativa, mas menor em comparação com outras bibliotecas mais populares.

  • react-window-infinite-loader:

    A documentação do react-window-infinite-loader é abrangente, mas pode ser mais técnica devido à complexidade da virtualização. A comunidade é forte, especialmente entre desenvolvedores que trabalham com listas grandes e otimização de desempenho.

  • react-infinite-scroller:

    O react-infinite-scroller possui uma boa documentação, com exemplos e guias que ajudam os desenvolvedores a entender suas funcionalidades. A comunidade é razoavelmente ativa, oferecendo suporte e recursos adicionais.

Como escolher: react-infinite-scroll-component vs react-window-infinite-loader vs react-infinite-scroller

  • react-infinite-scroll-component:

    Escolha o react-infinite-scroll-component se você precisa de uma solução simples e leve para implementar rolagem infinita, com suporte a eventos de rolagem e uma API fácil de usar. É ideal para projetos que não exigem uma complexidade adicional e onde a simplicidade é uma prioridade.

  • react-window-infinite-loader:

    Escolha o react-window-infinite-loader se você está lidando com listas muito grandes e precisa de uma solução que combine rolagem infinita com virtualização. Isso melhora o desempenho ao renderizar apenas os itens visíveis na tela, sendo ideal para aplicações que precisam de eficiência em listas extensas.

  • react-infinite-scroller:

    Escolha o react-infinite-scroller se você precisa de uma biblioteca que ofereça controle total sobre o carregamento de dados e suporte a callbacks para eventos de rolagem. É mais flexível e permite personalizações, sendo ideal para aplicações que requerem um gerenciamento mais detalhado do fluxo de dados.

README para react-infinite-scroll-component

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