Convert Figma logo to code with AI

ankeetmaini logoreact-infinite-scroll-component

An awesome Infinite Scroll component in react.

3,084
333
3,084
135

Top Related Projects

React components for efficiently rendering large lists and tabular data

React components for efficiently rendering large lists and tabular data

The most powerful virtual list component for React

6,875

🤖 Headless UI for Virtualizing Large Element Lists in JS/TS, React, Solid, Vue and Svelte

:scroll: A versatile infinite scroll React component.

Simple React Component That Makes Titles More Readable

Quick Overview

React-infinite-scroll-component is a lightweight and easy-to-use React component that implements infinite scrolling functionality. It automatically loads more content as the user scrolls down the page, providing a seamless and efficient way to handle large datasets in React applications.

Pros

  • Simple to implement and integrate into existing React projects
  • Supports both window and scrollable element infinite scrolling
  • Customizable loading and end messages
  • Handles both vertical and horizontal scrolling

Cons

  • Limited built-in styling options
  • May require additional optimization for very large datasets
  • Documentation could be more comprehensive
  • Lacks advanced features like virtualization for extremely long lists

Code Examples

  1. Basic usage with an array of items:
import InfiniteScroll from 'react-infinite-scroll-component';

function App() {
  const [items, setItems] = useState(Array.from({ length: 20 }));
  const [hasMore, setHasMore] = useState(true);

  const fetchMoreData = () => {
    if (items.length >= 500) {
      setHasMore(false);
      return;
    }
    setTimeout(() => {
      setItems(items.concat(Array.from({ length: 20 })));
    }, 500);
  };

  return (
    <InfiniteScroll
      dataLength={items.length}
      next={fetchMoreData}
      hasMore={hasMore}
      loader={<h4>Loading...</h4>}
    >
      {items.map((_, index) => (
        <div key={index}>
          div - #{index + 1}
        </div>
      ))}
    </InfiniteScroll>
  );
}
  1. Using with a scrollable element:
<div id="scrollableDiv" style={{ height: 300, overflow: "auto" }}>
  <InfiniteScroll
    dataLength={items.length}
    next={fetchMoreData}
    hasMore={hasMore}
    loader={<h4>Loading...</h4>}
    scrollableTarget="scrollableDiv"
  >
    {items.map((item, index) => (
      <div key={index}>{item}</div>
    ))}
  </InfiniteScroll>
</div>
  1. Customizing end message:
<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
  endMessage={
    <p style={{ textAlign: 'center' }}>
      <b>Yay! You have seen it all</b>
    </p>
  }
>
  {items.map((item, index) => (
    <div key={index}>{item}</div>
  ))}
</InfiniteScroll>

Getting Started

  1. Install the package:

    npm install react-infinite-scroll-component
    
  2. Import and use the component in your React application:

    import InfiniteScroll from 'react-infinite-scroll-component';
    
    function MyComponent() {
      // ... state and data fetching logic
    
      return (
        <InfiniteScroll
          dataLength={items.length}
          next={fetchMoreData}
          hasMore={hasMore}
          loader={<h4>Loading...</h4>}
        >
          {items.map((item, index) => (
            <div key={index}>{item}</div>
          ))}
        </InfiniteScroll>
      );
    }
    
  3. Implement the fetchMoreData function to load more items when the user scrolls.

Competitor Comparisons

React components for efficiently rendering large lists and tabular data

Pros of react-window

  • Highly performant for rendering large lists and grids
  • Supports both fixed and variable size items
  • Smaller bundle size and lower memory usage

Cons of react-window

  • Steeper learning curve and more complex API
  • Less out-of-the-box functionality (e.g., no built-in infinite loading)
  • Requires more manual configuration for advanced use cases

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</InfiniteScroll>

react-window:

<List
  height={400}
  itemCount={items.length}
  itemSize={35}
  width={300}
>
  {({ index, style }) => (
    <div style={style}>{items[index].name}</div>
  )}
</List>

react-infinite-scroll-component offers a simpler API with built-in infinite loading, while react-window provides more fine-grained control over rendering and better performance for large datasets. The choice between the two depends on the specific requirements of your project, such as list size, performance needs, and desired features.

React components for efficiently rendering large lists and tabular data

Pros of react-virtualized

  • More comprehensive solution for rendering large lists and tabular data
  • Offers additional components like Grid, Table, and WindowScroller
  • Better performance for very large datasets due to virtualization

Cons of react-virtualized

  • Steeper learning curve due to more complex API
  • Requires more setup and configuration
  • Larger bundle size compared to simpler infinite scroll solutions

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</InfiniteScroll>

react-virtualized:

<List
  width={300}
  height={300}
  rowCount={items.length}
  rowHeight={20}
  rowRenderer={({ index, key, style }) => (
    <div key={key} style={style}>
      {items[index].name}
    </div>
  )}
/>

react-virtualized offers more control over rendering and optimization but requires more setup. react-infinite-scroll-component provides a simpler API for basic infinite scrolling needs. Choose based on your project's complexity and performance requirements.

The most powerful virtual list component for React

Pros of react-virtuoso

  • More comprehensive virtualization solution, handling both windowing and infinite scrolling
  • Better performance for large datasets due to efficient rendering of visible items
  • Supports advanced features like grouped lists and customizable scroll containers

Cons of react-virtuoso

  • Steeper learning curve due to more complex API and configuration options
  • May be overkill for simple infinite scrolling use cases
  • Requires more setup and configuration compared to react-infinite-scroll-component

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</InfiniteScroll>

react-virtuoso:

<Virtuoso
  style={{ height: '400px' }}
  totalCount={items.length}
  itemContent={(index) => <div>{items[index].name}</div>}
  endReached={loadMore}
  overscan={200}
/>

react-virtuoso offers more control over rendering and performance optimization, while react-infinite-scroll-component provides a simpler API for basic infinite scrolling functionality. The choice between the two depends on the specific requirements of your project and the complexity of your list rendering needs.

6,875

🤖 Headless UI for Virtualizing Large Element Lists in JS/TS, React, Solid, Vue and Svelte

Pros of virtual

  • More flexible and powerful, supporting both infinite scrolling and virtual lists
  • Better performance for large datasets due to virtualization
  • Framework-agnostic, can be used with React, Vue, or vanilla JavaScript

Cons of virtual

  • Steeper learning curve and more complex setup
  • Requires more configuration and customization for specific use cases
  • May be overkill for simple infinite scrolling scenarios

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.name}</div>
  ))}
</InfiniteScroll>

virtual:

const virtualizer = useVirtualizer({
  count: items.length,
  getScrollElement: () => parentRef.current,
  estimateSize: () => 35,
});

return (
  <div ref={parentRef}>
    <div style={{ height: `${virtualizer.getTotalSize()}px` }}>
      {virtualizer.getVirtualItems().map((virtualItem) => (
        <div key={virtualItem.key}>{items[virtualItem.index].name}</div>
      ))}
    </div>
  </div>
);

Summary

react-infinite-scroll-component is simpler to use and ideal for basic infinite scrolling needs. virtual offers more advanced features and better performance for complex scenarios, but requires more setup and configuration. Choose based on your project's specific requirements and complexity.

:scroll: A versatile infinite scroll React component.

Pros of react-list

  • More flexible and customizable for complex list rendering scenarios
  • Supports both fixed and variable height items
  • Smaller bundle size, potentially better performance for large lists

Cons of react-list

  • Less straightforward implementation for simple infinite scrolling
  • Requires more manual configuration for loading states and error handling
  • May have a steeper learning curve for beginners

Code Comparison

react-infinite-scroll-component:

<InfiniteScroll
  dataLength={items.length}
  next={fetchMoreData}
  hasMore={hasMore}
  loader={<h4>Loading...</h4>}
>
  {items.map((item) => (
    <div key={item.id}>{item.title}</div>
  ))}
</InfiniteScroll>

react-list:

<ReactList
  itemRenderer={(index, key) => (
    <div key={key}>{items[index].title}</div>
  )}
  length={items.length}
  type='uniform'
/>

The react-infinite-scroll-component provides a more declarative API for infinite scrolling, while react-list offers greater control over rendering and optimization. react-list requires manual implementation of loading and error states, whereas react-infinite-scroll-component includes these features out of the box. Choose based on your specific requirements and level of customization needed.

Simple React Component That Makes Titles More Readable

Pros of react-wrap-balancer

  • Focuses on text wrapping and balancing, improving readability and aesthetics
  • Lightweight and specific to text layout optimization
  • Easy to implement for headings and short text blocks

Cons of react-wrap-balancer

  • Limited in scope compared to react-infinite-scroll-component's functionality
  • May not be as useful for long-form content or dynamic lists
  • Requires additional components for scrolling or pagination features

Code Comparison

react-wrap-balancer:

import Balancer from 'react-wrap-balancer'

function Heading() {
  return <Balancer>Your balanced heading text here</Balancer>
}

react-infinite-scroll-component:

import InfiniteScroll from 'react-infinite-scroll-component'

function List() {
  return (
    <InfiniteScroll dataLength={items.length} next={fetchMoreData} hasMore={true}>
      {items.map((item) => <div key={item.id}>{item.name}</div>)}
    </InfiniteScroll>
  )
}

The code comparison highlights the different purposes of these libraries. react-wrap-balancer is used to wrap and balance text content, while react-infinite-scroll-component is designed for implementing infinite scrolling functionality in lists or content feeds. The choice between these libraries depends on the specific needs of your project, whether it's optimizing text layout or handling large datasets with continuous scrolling.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

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 trigger a 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.
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.

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

💻

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

LICENSE

MIT

NPM DownloadsLast 30 Days