DEV Community

Aakash Kumar Chaudhary
Aakash Kumar Chaudhary

Posted on

Implementing infinite scrolling in react

Before we start coding, if you want to know more about what pagination is and why do we need it, do check out my blog here.

Let's say the ask is to display 50 items on the screen and whenever user reaches to the bottom, load next 50 items.
For that we need to keep track of the scroll position and keep on comparing it with the document body offsetHeight.

To get the scroll position, we will use window.scrollY.
Basically window.scrollY gives the number of pixels the page has been scrolled vertically from the top. It tells you how far down the page the user has scrolled.
Along with the window.scrollY, we will be using two more values to check if the user has reached at the bottom of the page or not.
window.innerHeight: This represents the height of the visible part of the window (the viewport). It's the height of the area that the user can currently see in the browser without scrolling.

document.body.offsetHeight: It gives the total height of the body element.

Code:

import { useState, useEffect } from "react";
import "./styles.css";
export default function App() {
  let query = [];
  let [items, setitems] = useState(50);
  for (let i = 1; i <= items; i++) {
    query.push(<p>{i}</p>);
  }

  useEffect(() => {
    const onScroll = () => {
      if (
        window.innerHeight + window.scrollY >=
        document.body.offsetHeight - 40
      ) {
        setitems(items + 50);
      }
    };

    window.addEventListener("scroll", onScroll);
    return () => window.removeEventListener("scroll", onScroll);
  }, [items]);

  return <div className="App">{query.map((q) => q)}</div>;
}
Enter fullscreen mode Exit fullscreen mode

Explanation: The first render of the page will trigger the useEffect hook which will add a scroll event. Whenever scrolling event happens, onScroll() method will be invoked and the it will check the position of the scroll. If it is at the bottom-40, then more 50 items is added to the items state.

Top comments (0)