Skip to content
PD
All insights

How to Implement Infinite Scrolling in React

Learn how to implement infinite scrolling in React using IntersectionObserver and API pagination. A practical guide to building seamless, dynamic user experiences.

How to Implement Infinite Scrolling in React

Infinite scrolling is a popular technique used in modern web applications to enhance user experience by loading content continuously as the user scrolls. Instead of paginating data manually, infinite scroll loads new content automatically, reducing the need for navigation and making browsing smoother.

In this article, we’ll walk through how to implement infinite scrolling in a React application using a simple API and the IntersectionObserver API.

Prerequisites
  • Basic knowledge of React
  • Node.js installed
  • A REST API that supports pagination (we’ll use a dummy one)

Step 1: Setup a New React App

If you don’t already have a React project, create one:

npx create-react-app react-infinite-scroll
cd react-infinite-scroll
npm start

Step 2: Create the Infinite Scroll Component

We’ll use JSONPlaceholder for mock data.

InfiniteScroll.js

import React, { useEffect, useRef, useState, useCallback } from 'react';

const InfiniteScroll = () => {
  const [posts, setPosts] = useState([]);
  const [page, setPage] = useState(1);
  const [hasMore, setHasMore] = useState(true);
  const loader = useRef(null);

  const fetchPosts = useCallback(async () => {
    const res = await fetch(`https://jsonplaceholder.typicode.com/posts?_limit=10&_page=${page}`);
    const data = await res.json();
    setPosts(prev => [...prev, ...data]);
    if (data.length === 0 || data.length < 10) {
      setHasMore(false);
    }
  }, [page]);

  useEffect(() => {
    fetchPosts();
  }, [fetchPosts]);

  useEffect(() => {
    if (!hasMore) return;
    const observer = new IntersectionObserver(entries => {
      if (entries[0].isIntersecting) {
        setPage(prev => prev + 1);
      }
    });
    if (loader.current) observer.observe(loader.current);

    return () => {
      if (loader.current) observer.unobserve(loader.current);
    };
  }, [hasMore]);

  return (
    <div style={{ padding: '1rem' }}>
      <h2>Infinite Scroll Posts</h2>
      <ul>
        {posts.map(post => (
          <li key={post.id} style={{ marginBottom: '1rem' }}>
            <strong>{post.title}</strong>
            <p>{post.body}</p>
          </li>
        ))}
      </ul>
      {hasMore && <div ref={loader}>Loading more...</div>}
    </div>
  );
};

export default InfiniteScroll;

Step 3: Use the Component

Modify App.js to use your infinite scroll component:

import React from 'react';
import InfiniteScroll from './InfiniteScroll';

function App() {
  return (
    <div className="App">
      <InfiniteScroll />
    </div>
  );
}

export default App;

How It Works

  • State Management: posts, page, and hasMore track content and pagination.
  • fetchPosts: Fetches 10 items per page and appends them to the list.
  • IntersectionObserver: Observes a div at the bottom of the list. When it enters the viewport, the page state increments, triggering new data fetch.

Tips & Best Practices

  • Debounce API calls if you have fast scroll behavior.
  • Handle API errors and edge cases like rate limits or server downtime.
  • Add loading skeletons for better UX.

Bonus: Add a Loader

You can replace the Loading more... line with a spinner or skeleton placeholder using a library like react-loading-skeleton or your own CSS.


Conclusion

With IntersectionObserver and a bit of state management, infinite scroll becomes a powerful and performant user experience feature. This pattern works for feeds, product listings, comment sections, and more.

// More insights

How to Implement Infinite Scrolling in React | Prabhat Dawadi