⬅
Infinite Scroll (React Query) And Intersection ObserverAymen Ben Zlaouia / July 15, 2025
2 min read • ––– views
Infinite Scroll in React with Intersection Observer and React Query
Infinite scroll is a popular UX pattern for loading data as the user scrolls, rather than all at once. In React, you can implement this efficiently using the Intersection Observer API and React Query. Let’s break down how this works, using the code from this project as a guide.
1. The Intersection Observer Hook#
The Intersection Observer API lets you detect when an element enters or leaves the viewport. In React, you can wrap this logic in a custom hook.
rootRef
is the scrollable container.ref
is the sentinel element at the end of your list.- When the sentinel is fully visible (
threshold: 1.0
), the callback fires — perfect for triggering a data fetch.
2. Fetching Data with React Query#
React Query’s useInfiniteQuery
makes paginated data fetching simple.
useInfiniteQuery
manages pages of users.getNextPageParam
controls when to stop fetching (after 5 pages here).
The fetchUsers
function makes a call to a public api to get a list of random users.
3. Putting It Together in the App#
In App.tsx
, you call the intersection observer and the query hooks:
- The sentinel
<li>
at the end of the list usessentinelRef
. - When it enters view, the next page is fetched if available.
The relevant JSX:
4. Why This Pattern?#
- Performance: Only loads what’s needed.
- User Experience: Seamless, no manual “Load More” button.
- Separation of Concerns: The Intersection Observer hook is reusable for any infinite scroll scenario.
5. Final Result#
Conclusion#
By combining the Intersection Observer API with React Query’s infinite queries, you get a robust, efficient infinite scroll solution in React. The hooks are reusable, and the logic is cleanly separated, making your codebase easier to maintain and extend.
GitHub Repository: https://github.com/aymoun95/infinite-scroll