Infinite scrolling in React

February 19, 20239 min read

React
JavaScript

So What is infinite scrolling?

Infinite scrolling is a technique used in web design to allow users to scroll through a large amount of content without having to navigate through multiple pages. It works by loading new content as the user scrolls down the page, dynamically updating the content as the user reaches the end of the current page.

How can we Implement this technique?

Infinite scrolling is often implemented using JavaScript, either by listening to scroll events or by using the IntersectionObserver API, which allows you to detect when an element enters or exits the viewport. When the user reaches the end of the current page, a new request is made to the server to load additional content, which is then appended to the existing content on the page.

Why do we need Infinite Scrolling?

Infinite scrolling is often used in social media platforms, such as Facebook, Twitter, and Instagram, as well as in e-commerce sites, blogs, and news sites. The goal is to provide a seamless user experience by eliminating the need to click through multiple pages to view more content.

Drawbacks of this technique.

Infinite scrolling has become a popular design trend, but it also has some drawbacks. One potential issue is that it can make it difficult for users to find specific content, as there is no clear navigation system to access different parts of the content. Additionally, infinite scrolling can cause performance issues if large amounts of content are loaded at once, which can slow down the user’s device or network or if the list become too large and user starts experiencing leg while scrolling.

Let’s Start.

Here’s an example of how to implement infinite scrolling using the IntersectionObserver API in a React:

import { useState, useEffect, useRef } from "react"
import "./App.scss"
import CollegeCard from "./components/college-card/college-card"
import { Loader } from "./components/presentational/loader/loader"
import { getCollegeList } from "./services/get-college-list"

function App() {
  const loadingRef = useRef(null)
  const [isLoading, setIsLoading] = useState(true)
  const [page, setPage] = useState(-1)
  const [colleges, setColleges] = useState([])

  useEffect(() => {
    const options = {
      root: null,
      rootMargin: "20px",
      threshold: 1.0,
    }
    const observer = new IntersectionObserver(handleObserver, options)
    if (loadingRef.current) {
      observer.observe(loadingRef.current)
    }
  }, [])
  const handleObserver = entities => {
    const target = entities[0]
    if (target.isIntersecting) {
      setPage(page => page + 1)
    }
  }
  useEffect(() => {
    ;(async () => {
      if (page > -1) {
        setIsLoading(true)
        const collegeList = await getCollegeList(page)
        if (collegeList.length === 0) {
          setIsLoading(false)
        } else {
          setColleges(c => [...c, ...collegeList])
        }
      }
    })()
  }, [page])
  return (
    <div className="container">
      <h2>Colleges in North India</h2>
      <div className="cards">
        {Array.isArray(colleges) &&
          colleges.map((college, i) => (
            <CollegeCard key={i} college={college} />
          ))}
      </div>
      {
        <div ref={loadingRef} style={{ display: isLoading ? "block" : "none" }}>
          <Loader />
        </div>
      }
    </div>
  )
}

export default App

Take a look at this Demo which is using this code written above.


Vishal Sharma

Hey there! This is Vishal Sharma. I reside and work at Gurgaon, India. I am a Software Engineer and primarily works with JavaScript, ReactJS and NodeJS.
LinkedIn Link

Welcome to my Javascript tech blog! Here, you'll find the latest news and updates in the world of Javascript, as well as tutorials and resources to help you improve your coding skills. From learning the basics of Javascript to advanced concepts like object-oriented programming, I post something for developers of all levels. Whether you're just starting out or you're a seasoned pro, you'll find valuable insights and information on our blog. So stay up-to-date with the latest in Javascript technology by bookmarking this page and checking back often.
Thank you for visiting!