How do you implement an infinite scrolling list in React

0 votes

How do you implement an infinite scrolling list in React?

I am creating a React app. I want to achieve infinite scrolling so that more items automatically load up because the user scrolls down. What is the best practice for this method, in terms of least performance issues and good integration of new data?

Oct 21, 2024 in Web Development by Nidhi
• 8,120 points
193 views

1 answer to this question.

0 votes

Imagine you’re reading a long article online. Instead of having to click “Next Page” every time you reach the bottom, the page just keeps loading more content as you scroll down. This is called infinite scrolling.

Let’s see how to do it in React:

import React, { useState, useEffect } from 'react';

const InfiniteScrollList = () => {

  const [items, setItems] = useState([]); // List of items

  const [page, setPage] = useState(1); // Tracks the current page

  const [loading, setLoading] = useState(false); // Loading state

  const [error, setError] = useState(null); // Error state for handling fetch errors


  // Fetch more items whenever the page changes

  useEffect(() => {

    fetchMoreItems();

  }, [page]);


  const fetchMoreItems = async () => {

    setLoading(true);

    setError(null); // Reset error state before new fetch

    try {

      const newItems = await fakeApiCall(page);

      setItems(prevItems => [...prevItems, ...newItems]);

    } catch (err) {

      setError('Error fetching items');

    } finally {

      setLoading(false); // Ensure loading is reset after fetch attempt

    }

  };


  // Handle scroll to detect if the user has reached the bottom

  const handleScroll = () => {

    if (

      window.innerHeight + document.documentElement.scrollTop >=

        document.documentElement.offsetHeight - 50 &&

      !loading

    ) {

      setPage(prevPage => prevPage + 1); // Load the next page

    }

  };


  // Attach the scroll event listener when the component mounts

  useEffect(() => {

    window.addEventListener('scroll', handleScroll);

    return () => window.removeEventListener('scroll', handleScroll); // Cleanup on unmount

  }, []);


  return (

    <div>

      <ul>

        {items.map(item => (

          <li key={item.id}>{item.name}</li>

        ))}

      </ul>

      {loading && <p>Loading more, please wait...</p>}

      {error && <p style={{ color: 'red' }}>{error}</p>} {/* Display error if any */}

    </div>

  );

};


// Simulated API call (returns 10 new items per page)

const fakeApiCall = page => {

  return new Promise(resolve => {

    setTimeout(() => {

      const newItems = Array.from({ length: 10 }, (_, index) => ({

        id: page * 10 + index,

        name: `Item ${page * 10 + index}`,

      }));

      resolve(newItems);

    }, 1000);

  });

};


export default InfiniteScrollList;
Related Question : Implement role-based access control in a full-stack application
answered Oct 25, 2024 by kavya

Related Questions In Web Development

0 votes
0 answers

How do you implement an infinite scrolling list in React?

How do you implement an infinite scrolling ...READ MORE

Oct 11, 2024 in Web Development by anonymous
• 8,120 points

edited Oct 14, 2024 by Hoor 320 views
0 votes
0 answers

How do you implement role-based access control (RBAC) in a full stack application?

How do you implement role-based access control ...READ MORE

Oct 14, 2024 in Web Development by anonymous
• 8,120 points
113 views
0 votes
1 answer
0 votes
1 answer

How do you set the document title in React?

Suppose we are reading an article online. ...READ MORE

answered Oct 21, 2024 in Web Development by Navya
• 460 points
318 views
0 votes
1 answer
+1 vote
1 answer

Authentication versus Authorization

Authentication is basically used to find are ...READ MORE

answered Jun 25, 2019 in Others by sunshine
• 1,300 points
924 views
0 votes
0 answers

How should I implement lazy loading for my images in react?

Oct 11, 2024 in Web Development by anonymous
• 8,120 points
123 views
0 votes
0 answers

How do you set the document title in React?

Oct 11, 2024 in Web Development by anonymous
• 8,120 points
114 views
0 votes
1 answer

How do you implement API request validation in Express using middleware?

To implement API request validation in Express ...READ MORE

answered Nov 19, 2024 in Web Development by kavya
116 views
0 votes
1 answer

How do you detect memory leaks in Angular and fix them?

Imagine your computer is a room and ...READ MORE

answered Oct 25, 2024 in Web Development by kavya
233 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP