MCPcopy
hub / github.com/ankeetmaini/react-infinite-scroll-component

github.com/ankeetmaini/react-infinite-scroll-component @v7.2.1 sqlite

repository ↗ · DeepWiki ↗ · release v7.2.1 ↗
37 symbols 77 edges 27 files 2 documented · 5%
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

API When to use
InfiniteScroll component Most cases, handles loader, endMessage, pull-to-refresh, inverse scroll UI
useInfiniteScroll hook Custom UI, you own the markup, the hook manages the observer

InfiniteScroll 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={

Loading...

}
      endMessage={

All items loaded.

}
    >
      {items.map((item) => (


{item.name}


      ))}
    </InfiniteScroll>
  );
}

Scroll inside a fixed-height container




  <InfiniteScroll
    dataLength={items.length}
    next={fetchMore}
    hasMore={hasMore}
    loader={

Loading...

}
    scrollableTarget="scrollableDiv"
  >
    {items.map((item) => (


{item.name}


    ))}
  </InfiniteScroll>



Pass a ref value directly instead of a string id:

const containerRef = useRef<HTMLDivElement>(null);




  <InfiniteScroll
    dataLength={items.length}
    next={fetchMore}
    hasMore={hasMore}
    loader={

Loading...

}
    scrollableTarget={containerRef.current}
  >
    {items.map((item) => (


{item.name}


    ))}
  </InfiniteScroll>


;

Inverse scroll (chat / messaging UIs)




  <InfiniteScroll
    dataLength={messages.length}
    next={loadOlderMessages}
    hasMore={hasMore}
    loader={

Loading older messages...

}
    inverse={true}
    scrollableTarget="chatBox"
    style={{ display: 'flex', flexDirection: 'column-reverse' }}
  >
    {messages.map((msg) => (


{msg.text}


    ))}
  </InfiniteScroll>



Pull-to-refresh

<InfiniteScroll
  dataLength={items.length}
  next={fetchMore}
  hasMore={hasMore}
  loader={

Loading...

}
  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) => (


{item.name}


  ))}
</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={

Loading...

}
      endMessage={

You have seen everything.

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

Loading...

 : null}
      endMessage={

All posts loaded.

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

Loading...

}
    >
      {posts.map((post) => (


{post.title}


      ))}
    </InfiniteScroll>
  );
}

Three scroll modes

Mode How to use Use case
Window scroll Omit height and scrollableTarget Social feeds, blogs, product listings
Fixed-height container Pass height prop Embedded lists, sidebars
Custom scrollable parent Pass scrollableTarget (element or id) Existing overflow containers

Props, InfiniteScroll

Prop Type Required Default Description
dataLength number yes - Current count of rendered items. The component resets its load guard each time this value changes, which allows next() to fire again on the next scroll.
next () => void yes - Called once when the sentinel enters the viewport. Append new items to your list state inside this callback; do not replace the existing items.
hasMore boolean yes - When false, the observer is disconnected and next() will not be called again. Set it to false when your data source has no more pages.
loader ReactNode yes - Rendered below the list while the next page is loading. Displayed between the last item and the bottom sentinel.
endMessage ReactNode no - Rendered below the list when hasMore is false. Use it for an "all caught up" or "no more items" message.
height number \| string no - Creates a fixed-height scroll container wrapping the list. Accepts a pixel number or any CSS length string. Omit this prop to scroll the window instead.
scrollableTarget HTMLElement \| string \| null no - The scrollable ancestor that already provides overflow scrollbars. Pass the element's id string or a direct HTMLElement reference. Required when the scroll container is neither the window nor the height wrapper.
scrollThreshold number \| string no 0.8 How close to the bottom the user must scroll before next() is called. A fraction like 0.8 means 80% scrolled; a string like "200px" means within 200 px of the bottom edge.
inverse boolean no false Reverse scroll direction for chat or messaging UIs. The sentinel moves to the top of the list. Use together with flexDirection: column-reverse on the scroll container.
pullDownToRefresh boolean no false Enable pull-to-refresh gesture on touch and mouse. Requires refreshFunction to also be set.
refreshFunction () => void no - Called once when the user pulls down past pullDownToRefreshThreshold pixels and releases. Only active when pullDownToRefresh is true.
pullDownToRefreshThreshold number no 100 How many pixels the user must pull down before refreshFunction is triggered on release.
pullDownToRefreshContent ReactNode no - Content shown inside the pull-to-refresh area while the user is pulling but has not yet reached the threshold.

Extension points exported contracts — how you extend this code

UseInfiniteScrollOptions (Interface)
(no doc)
src/useInfiniteScroll.ts
Props (Interface)
(no doc)
src/index.tsx
UseInfiniteScrollResult (Interface)
(no doc)
src/useInfiniteScroll.ts

Core symbols most depended-on inside this repo

buildRootMargin
called by 11
src/utils/buildRootMargin.ts
parseThreshold
called by 6
src/utils/threshold.ts
useInfiniteScroll
called by 3
src/useInfiniteScroll.ts
InfiniteScroll
called by 0
src/index.tsx
handler
called by 0
src/index.tsx
onStart
called by 0
src/index.tsx
onMove
called by 0
src/index.tsx
onEnd
called by 0
src/index.tsx

Shape

Class 12
Function 11
Method 11
Interface 3

Languages

TypeScript100%

Modules by API surface

src/__tests__/setup/intersectionObserverMock.ts8 symbols
src/index.tsx6 symbols
src/useInfiniteScroll.ts3 symbols
src/stories/WindowInfiniteScrollComponent.tsx3 symbols
src/stories/ScrollableTop.tsx3 symbols
src/stories/ScrollableTargetInfScroll.tsx3 symbols
src/stories/PullDownToRefreshInfScroll.tsx3 symbols
src/stories/InfiniteScrollWithHeight.tsx3 symbols
src/__tests__/useInfiniteScroll.test.tsx2 symbols
src/utils/threshold.ts1 symbols
src/utils/buildRootMargin.ts1 symbols
src/stories/UseInfiniteScrollHook.tsx1 symbols

Dependencies from manifests, versioned

@babel/core7.20.0 · 1×
@babel/preset-env7.28.5 · 1×
@babel/preset-react7.28.5 · 1×
@babel/preset-typescript7.28.5 · 1×
@rollup/plugin-node-resolve15.0.0 · 1×
@rollup/plugin-typescript11.0.0 · 1×
@size-limit/preset-small-lib12.0.1 · 1×
@storybook/addon-essentials7.6.0 · 1×
@storybook/react7.6.0 · 1×
@storybook/react-webpack57.6.0 · 1×
@testing-library/react12.1.5 · 1×
@types/jest29.5.14 · 1×

For agents

$ claude mcp add react-infinite-scroll-component \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact