Have you ever come across a website or app that loads and displays more content as you scroll? This is what we call infinite scroll.

Infinite scroll is a popular technique that can make it easier to browse large amounts of content. It can also make for a smoother user experience, especially on mobile devices.

Implementing Infinite Scroll in React.js

You can implement infinite scroll in React in a few different ways. The first is to use a library like react-infinite-scroll-component. This library’s component triggers an event whenever the user scrolls to the bottom of the page. You can then use this event as a cue to load more content.

Another way to implement infinite scroll in React is via its built-in functions. One such function is “componentDidMount,” which React calls when it first mounts a component.

You can use this function to load the first batch of data, followed by the “componentDidUpdate” function to load subsequent data as the user scrolls down.

You can also use React hooks to add an infinite scrolling feature.

Using the react-infinite-scroll-component Library

There are a few ways to use the react-infinite-scroll-component.

Install react-infinite-scroll-component

To kickstart the usage, you first need to install it via npm:

        npm install react-infinite-scroll-component --save
    

Import react-infinite-scroll-component into React

After installation, you need to import the infinite scroll library into your React component.

        import React from 'react'
import InfiniteScroll from 'react-infinite-scroll-component'
 
class App extends React.Component {
  constructor() {
    super()
    this.state = {
      items: [],
      hasMore: true
    }
  }

  componentDidMount() {
    this.fetchData(1)
  }
 
  fetchData = (page) => {
    const newItems = []
 
    for (let i = 0; i < 100; i++) {
      newItems.push(i )
    }
 
    if (page === 100) {
      this.setState({ hasMore: false })
    }
 
    this.setState({ items: [...this.state.items, ...newItems] })
  }
 
  render() {
    return (
      <div>
        <h1>Infinite Scroll</h1>
        <InfiniteScroll
          dataLength={this.state.items.length}
          next={this.fetchData}
          hasMore={this.state.hasMore}
          loader={<h4>Loading...</h4>}
          endMessage={
            <p style={{ textAlign: 'center' }}>
              <b>Yay! You have seen it all</b>
            </p>
          }
        >
          {this.state.items.map((item, index) => (
            <div key={index}>
              {item}
            </div>
          ))}
        </InfiniteScroll>
      </div>
    )
  }
}
 
export default App

This code starts by importing React and the InfiniteScroll component from the react-infinite-scroll-component library. It then creates a stateful component and initializes it with an empty items array and a hasMore flag set to True.

Set Parameters

In the componentDidMount lifecycle method, you must call the fetchData method with a page parameter set to 1. The fetchData method makes an API call to fetch data. This react-infinite-scroller example generates some dummy data and creates an array of 100 items.

Once the page parameter reaches 100, since no more items exist, you can set the hasMore flag to False. This stops the InfiniteScroll component from making further API calls. Finally, set the state using the new data.

The render method uses the InfiniteScroll component and passes in some props. The dataLength prop is set to the length of the items array. The following prop is set to the fetchData method. The hasMore prop is set equal to the hasMore flag.

The loader prop causes the component to render its contents as a loading indicator. Likewise, it will render the endMessage prop as a message when all the data has finished loading.

You can pass other props to the InfiniteScroll component, but these are the ones you'll use most often.

react app with infinite scroll using third party packages

Using Built-In Functions

React also has some built-in methods that you can use to implement InfiniteScroll.

The first method is componentDidUpdate. React calls this method after it updates a component. You can use this method to check if the user has scrolled to the bottom of the page. If yes, it loads more data.

The second method is scroll, which React calls when the user scrolls. You can use this method to keep track of the scroll position. You can load more data if the user has scrolled to the bottom of the page.

Here's a React infinite scroll example that shows you how to use these methods:

        import React, {useState, useEffect} from 'react'
 
function App() {
  const [items, setItems] = useState([])
  const [hasMore, setHasMore] = useState(true)
  const [page, setPage] = useState(1)
 
  useEffect(() => {
    fetchData(page)
  }, [page])
 
  const fetchData = (page) => {
    const newItems = []
 
    for (let i = 0; i < 100; i++) {
      newItems.push(i)
    }
 
    if (page === 100) {
      setHasMore(false)
    }
 
    setItems([...items, ...newItems])
  }
 
  const onScroll = () => {
    const scrollTop = document.documentElement.scrollTop
    const scrollHeight = document.documentElement.scrollHeight
    const clientHeight = document.documentElement.clientHeight
 
    if (scrollTop + clientHeight >= scrollHeight) {
      setPage(page + 1)
    }
  }
 
  useEffect(() => {
    window.addEventListener('scroll', onScroll)
    return () => window.removeEventListener('scroll', onScroll)
  }, [items])
 
  return (
    <div>
      {items.map((item, index) => (
        <div key={index}>
          {item}
        </div>
      ))}
    </div>
  )
}
 
export default App

This code uses the useState and useEffect hooks to manage state and side effects.

Within the useEffect hook, it calls the fetchData method with the current page. The fetchData method makes an API call to fetch data. In this example, you're just generating some dummy data to demonstrate the technique.

The for loop populates the newItems array with 100 integers. If the page parameter is 100, it sets the hasMore flag to False. This stops the infinite scroll component from making further API calls.

Finally, set the state with the new data.

The onScroll method keeps track of the scroll position. You can load more data if the user scrolls to the page's bottom.

The useEffect hook adds an event listener for the scroll event. When the scroll event fires, it calls the onScroll method.

react app screen with infinite scroll using in-built features

The Pros and Cons of Infinite Scroll in React

There are pros and cons to using React's infinite scroll. It improves the user interface, making for a smoother experience, especially on mobile devices. However, it can also lead to users missing content as they may not scroll down far enough to see it.

It is essential to weigh up the pros and cons of the infinite scroll technique before implementing it on your website or app.

Improve User Experience With Infinite Scroll in React.js

Adding infinite scroll to your React.js website or app can improve the user experience. With infinite scroll, users don't have to click to see more content. Using Infinite Scroll in your React.js app can reduce the number of page loads, which further improves performance.

You can also easily deploy your React app to Github pages for free.