Problem Statement
Traditional pagination requires users to manually click "Next Page" links to view more content, interrupting their browsing experience. Infinite scrolling solves this by automatically loading the next set of items as the user nears the bottom of the visible page.
Your task is to build a reusable InfiniteScroll list in React. Using the browser's native IntersectionObserver API, your component must detect when the user is approaching the end of the loaded list, trigger a paginated fetch request to load more items, and append them without resetting scroll position.
Requirements
Functional
- Dynamic Append: Render a list of items and dynamically append additional batches of mock items when the user scrolls near the bottom.
- Scroll Sensor: Place an invisible sentinel or "sensor" element at the bottom of the list and observe it using an
IntersectionObserver. - Async Loading State: Show a loading indicator/spinner at the bottom while waiting for the next page to resolve.
- Stop Trigger / End of Data: Stop observing the sentinel and display a "You've reached the end" message once the mock API reports that no more pages are available.
- Fetch Locking: Ensure that if a fetch request is currently active, additional scroll triggers do not spawn concurrent, duplicate fetches for the same page.
Non-Functional
- The component must clean up and disconnect the observer reference whenever it unmounts or completes loading all items.
- Provide an adjustable
thresholdorrootMarginto trigger the observer slightly before the sentinel hits the viewport, making the scroll feel seamless. - Style the list and cards nicely with Tailwind CSS.
Concepts Tested
- Monitoring DOM layouts using the
IntersectionObserverAPI. - React Refs (
useRef) to track observer instances and DOM nodes. - Managing paginated API state (page counts, loading locks, total limits).
- Dynamic rendering and layout stability.
