How to implement infinite scrolling with React.js

Key takeaways:

  • To implement infinite scrolling in React, we can either design a custom infinite scroller or use a third-party library such as react-infinite-scroll or react-infinite-scroll-hook.

  • The Intersection Observer API is ideal for detecting when a target element becomes visible in the viewport, making it efficient for infinite scrolling.

  • In a custom implementation, React hooks like useState, useEffect, and useRef are essential for managing state, triggering side effects, and referencing DOM elements.

  • The callback function of the Intersection Observer API executes when the observed element meets the threshold condition, updating the list of items.

  • Infinite scrolling provides a seamless user experience by dynamically loading content without pagination.

What is infinite scrolling?

Infinite scrolling, also known as endless scrolling or continuous scrolling, is a technique for loading and displaying content progressively as the user scrolls down a web page or through a list or feed of items. This Answer will guide us through implementing infinite scrolling in React.js using a custom solution with the Intersection Observer API.

Note: If you’re new to React, consider reading our detailed blog, A Step-by-Step Guide To Learn React, to get familiar with core concepts like functional components and hooks, which will help you better understand the code in this tutorial.

React infinite scrolling methods

There are two ways to implement infinite scrolling in React applications:

  • Design a custom infinite scroller.

  • Use a third-party library such as react-infinite-scroll or react-infinite-scroll-hook.

In this Answer, we will focus on building a custom infinite scroll in React using the Intersection Observer API.

What is the Intersection Observer API?

The Intersection Observer API is a web platform API that allows developers to monitor changes in the intersection of a target element with its parent element or the viewport. It is a powerful tool for efficiently detecting when an element enters or exits the user’s viewport or intersects with other elements. This is useful for implementing features like infinite scroll in React and tracking the visibility of elements on a web page.

Implementing a custom infinite scroller in React

Using a simple React application, we’ll import a functional component into our App.js for a React infinite scrolling example.

Create a React functional component

In this section, we’ll implement a React functional component named InfiniteScroll. We’ll create a file named InfiniteScroll.js to import three hooks: useState, useEffect, and useRef.

import { useEffect, useState, useRef } from 'react'

Next, we’ll define the function, InfiniteScroll, which defines the following three constant variables:

  • items: Stores the list of items rendered on the web page. It uses the useState hook to manage and store data.

  • data: Defines dummy data for this React infinite scroll tutorial. We can replace it with our data.

  • target: Defines a target element. The Intersection Observer API will observe it as a ref. It uses the useRef hook, which allows us to manipulate a DOM element.

export default function InfiniteScroll (){
const [items, setItems] = useState([]);
const data = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6'];
const target = useRef(null);
}

When the component mounts, we’ll use the useEffect hook to initialize the items state with the initial data. The following code runs once when the component is first rendered:

useEffect(() => {
setItems((prevItems) => [...prevItems, ...data]);
})
The useEffect hook to populate the data in an items list

Next, we’ll use the useEffect hook to implement the infinite scroll behavior, which depends on target. This function will initialize an InteresectionObserver object of the Intersection Observer API named observer.

useEffect(() => {
const observer = new IntersectionObserver(
entries => {
if (entries[0].isIntersecting) {
setItems((prevItems) => [...prevItems, ...data]);
}
},
{ threshold: 1 }
);
if (target.current) {
observer.observe(target.current);
}
return () => {
if (target.current) {
observer.unobserve(target.current);
}
};
}, [target]);
The useEffect hook to implement the IntersectionObserver object

We’ll define two parameters in its constructor:

  • First is the callback function, which accepts an array of objects of the IntersectionObserver called entries. This function is called when the observed elements intersect with the viewport. Each object in the array, entries, describes the state of the observed elements. As we observe only one element we will implement the condition for entries[0]. If entries[0] intersects with the viewport, its isIntersecting property is set to true. So, as soon as entries[0] is visible on the screen, the useEffect hook is triggered, and items are updated.

  • Second is the threshold value, which describes when the callback function should be triggered. Its value ranges from 0.0 to 1.0. A value of 1 indicates that the callback function will be triggered when the observed element is 100% visible on the viewport.

As we progress, we’ll assign the Intersection Observer (observer) to observe the target. The condition checks whether the target exists.

if (target.current) {
observer.observe(target.current);
}
Set the observer to observe the target

Finally, the effect hook returns a function to stop observing the target when the component unmounts or when target changes.

return () => {
if (target.current) {
observer.unobserve(target.current);
}
};
Set the observer to un observe target

The InfiniteScroll function returns an object that includes items (the list of rendered items) and target (a reference to the element observed for intersection), which can be used within another component to display the items and set up the target element.

Import the component in app.js

Moving on, in the app.js file, we’ll import the InfiniteScroll component to create a seamless infinite scroll experience in React.

import InfiniteScroll from './InfiniteScroll'

In the function App, we’ll unpack the returned array containing the items and the target.

const { items, target } = InfiniteScroll()

The function will return a div, which lists the items in an unordered list.

<ul>
{items.map((item) => <li>{item}</li>)}
</ul>
Unordered list of items

div contains another div that acts as our target.

<div ref={target}></div>

Therefore, when the user scrolls to the bottom of the rendered list, and the target intersects with the viewport, the list is populated again with the data.

Run the application below to see the output.

import { useEffect, useState, useRef } from 'react'

export default function InfiniteScroll (){
  const [items, setItems] = useState([]);
  const data = ['item1', 'item2', 'item3', 'item4', 'item5', 'item6'];
  const target = useRef(null);

  useEffect(() => {
    setItems((prevItems) => [...prevItems, ...data]);
  })

  useEffect(() => {
    const observer = new IntersectionObserver(
      entries => {
        if (entries[0].isIntersecting) {
          setItems((prevItems) => [...prevItems, ...data]);
        }
      },
      { threshold: 1 }
    );

    if (target.current) {
      observer.observe(target.current);
    }

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


React application with infinite scroll

In the React infinite scrolling example given above, the data is recursively populated in the list items as soon as the target is rendered on the screen.

Knowledge test

Let’s attempt a short quiz to assess our understanding.

Q

What is the primary purpose of using the Intersection Observer API when implementing infinite scrolling in React?

A)

To manage state changes of React components

B)

To detect when an element is visible within the viewport

C)

To create complex animations for scrolling effects

D)

To fetch data from an external API directly

Ready to bring your web development skills to life? With Build an E-learning Website with the MERN Stack, you’ll create a dynamic course catalog site, mastering database design, API development, and seamless frontend-backend integration.

Conclusion

Infinite scrolling is a useful user interface design pattern commonly used in websites and applications. Instead of presenting the user with pagination controls to navigate different content pages, infinite scroll provides a seamless and continuous browsing experience. In a real-world scenario, we might replace the static data array with a function to fetch more items from an API, making it even more dynamic and responsive. This custom infinite scroll in React can improve the user experience, making it a great alternative to traditional pagination.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How to make an infinite slider in React

To create an infinite slider in React, you can use a combination of state management and CSS transitions to loop through a list of items. Use useState to keep track of the current slide index, and useEffect to automatically change the index over time. You can also handle swipe events or buttons for manual navigation. For a smoother experience, consider using libraries like react-slick or customizing the logic for wrapping back to the first slide after the last.


Is infinite scroll bad for SEO?

Infinite scroll can be challenging for SEO because search engine crawlers may not be able to load all the content that appears only after scrolling. If not implemented properly, important content may remain hidden and unindexed. However, you can optimize infinite scroll for SEO by ensuring that content is accessible through separate paginated URLs, allowing search engines to access all the content.


How do you implement infinite scroll in a React table?

To implement infinite scroll in a React table, you can use the Intersection Observer API or listen for scroll events. Monitor the visibility of the bottom element of the table or the scrolling position, and when it becomes visible or reaches a threshold, load more rows and update the state with the new data. This allows the table to fetch and render additional data as the user scrolls down.


Is infinite scroll lazy loading?

Yes, infinite scroll is a form of lazy loading, as it loads additional content dynamically as the user scrolls down the page rather than loading everything at once. It optimizes the initial page load time by only loading visible content first and fetching more data when required. However, lazy loading can also apply to other elements like images, where content is loaded only when needed for a better user experience.


Is infinite scroll good or bad?

  • Infinite scroll is good when user engagement and content discovery are the primary goals where users are exploring and not performing targeted searches. For example when browsing the social media, news feeds, entertainment sites, or image galleries.
  • Infinite scroll may not be suitable for tasks requiring precise navigation, comparisons, or heavy processing. For instance, e-commerce websites users often need to compare products and make specific purchases, which is easier with pagination. Infinite scroll is also not suitable for resource constrained environments because if the content is too resource-intensive, loading it dynamically may cause it to exceed users’ bandwidth limits.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved