DEV Community

Krunal Kanojiya
Krunal Kanojiya

Posted on

How to create infinite scroll with fetch data from api in ReactJS

What is infinite scroll

Infinite scroll is a web design technique that allows a website to load new content continuously as the user scrolls down the page, eliminating the need for pagination. As the user approaches the bottom of the page, the next batch of content is automatically loaded, creating the illusion of an endless stream of information. This can be a convenient way to present a large amount of content to the user without overwhelming them with pagination links, but it can also make it difficult for users to locate specific content or navigate back to previous content.

Example

First, create a component called “InfiniteScroll” that will handle the infinite scroll functionality:

import React, { useState, useEffect } from 'react';
const InfiniteScroll = ({ fetchData, renderData, hasMore }) => {
  const [page, setPage] = useState(1);
  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => window.removeEventListener('scroll', handleScroll);
  }, []);
  useEffect(() => {
    if (hasMore) {
      fetchData(page);
      setPage(page + 1);
    }
  }, [page]);
  const handleScroll = () => {
    if (
      window.innerHeight + document.documentElement.scrollTop
      === document.documentElement.offsetHeight
    ) {
      fetchData(page);
      setPage(page + 1);
    }
  };
  return <div>{renderData()}</div>;
};
export default InfiniteScroll;
Enter fullscreen mode Exit fullscreen mode

Next, create a component that will use the InfiniteScroll component and handle the API fetching:

import React, { useState, useEffect } from 'react';
import InfiniteScroll from './InfiniteScroll';
const DataList = () => {
  const [data, setData] = useState([]);
  const [hasMore, setHasMore] = useState(true);
  const fetchData = (page) => {
    fetch(`https://api.example.com/data?page=${page}`)
      .then((res) => res.json())
      .then((res) => {
        if (res.length === 0) {
          setHasMore(false);
        } else {
          setData([...data, ...res]);
        }
      });
  };
  const renderData = () => {
    return data.map((item) => (
      <div key={item.id}>{item.name}</div>
    ));
  };
  return (
    <InfiniteScroll
      fetchData={fetchData}
      renderData={renderData}
      hasMore={hasMore}
    />
  );
};

Enter fullscreen mode Exit fullscreen mode

Finally, use the DataList component in your main component:

import React from 'react';
import DataList from './DataList';
const App = () => {
  return (
    <div>
      <DataList />
    </div>
  );
};
export default App;

Enter fullscreen mode Exit fullscreen mode

This will create an infinite scroll component that fetches data from an API and renders it as the user scrolls down the page. The component will stop fetching data when there are no more results to be fetched from the API.

Top comments (0)