Create a React component that implements infinite scrolling functionality. The component should fetch and display images from an external API as the user scrolls down the page. When the last image in the currently loaded set becomes visible in the viewport, the next set of images should be fetched and displayed.
-
State Management:
data
: An array to store the fetched image data.pageNo
: A number to keep track of the current page number for API requests.
-
Fetching Data:
- Use the
useEffect
hook to fetch data from the API wheneverpageNo
changes. - Append the newly fetched data to the existing data to maintain a cumulative list of images.
- Use the
-
Handling Infinite Scroll:
- Use another
useEffect
hook to set up anIntersectionObserver
. - The observer checks if the last image in the list is visible in the viewport.
- When the last image becomes visible, increment
pageNo
to trigger the next data fetch.
- Use another
-
Cleanup:
- Ensure proper cleanup of the observer when the component unmounts or when the observed element changes.
To append new data:
setData((prevData) => [...prevData, ...data]);