How to Implement Infinite Scroll in React: A Step-by-Step Tutorial
Infinite scroll loads additional content as the user scrolls down, creating a seamless browsing experience. In React, the Intersection Observer API offers a performant way to detect when a user reaches the bottom of a list. This tutorial will guide you through implementing it without external libraries.
We’ll use a custom hook to observe a sentinel element. When it becomes visible, we fetch more data and update the state. This approach avoids manual scroll event listeners and improves performance.
1. Create the Observer Hook
Build a reusable useInfiniteScroll hook that accepts a callback and an optional target ref.
- Use
useRefto create the sentinel element. - Inside
useEffect, instantiate anIntersectionObserverwith a threshold of 1.0. - When the sentinel intersects, call the provided callback.
- Return the sentinel ref so you can attach it to a div at the bottom of your list.
2. Integrate with Data Fetching
In your main component, manage page and items state. The callback from the hook should increment the page and fetch the next set of data.
- Use
useEffectto call your API wheneverpagechanges. - Append new items to the existing list using spread.
- Set a loading flag to show a spinner while fetching.
3. Handle Edge Cases
Prevent duplicate fetches and manage errors.
- Add a
hasMoreboolean from the API response to stop observing. - Use a loading guard: do not fire the callback if already loading.
- Display an error message and allow retry if the fetch fails.
4. Cleanup on Unmount
Always disconnect the observer inside the useEffect cleanup function to avoid memory leaks and unwanted callbacks after the component unmounts.
Implementing infinite scroll with Intersection Observer is efficient and simple. You get smooth, native-like scrolling without expensive scroll listeners. Test with different threshold values to fineātune when the next batch should load. This pattern works well for feeds, galleries, and any paginated list.