Blog>
Snippets

Implementing Infinite Scroll with React Query

Implement an infinite scroll feature in a React application, using React Query to fetch and append data as the user scrolls.
import { useInfiniteQuery } from 'react-query';
import axios from 'axios';
import React, { useEffect } from 'react';
Initial setup for using useInfiniteQuery from React Query, axios for fetching data, and React for handling effects.
const fetchProjects = async ({ pageParam = 0 }) => {
  const response = await axios.get(`/api/projects?cursor=${pageParam}`);
  return response.data;
};
Defines the asynchronous function to fetch projects data from the API, accepting a pageParam as the cursor for pagination.
const { data, hasNextPage, fetchNextPage, isFetchingNextPage } = useInfiniteQuery('projects', fetchProjects, {
  getNextPageParam: (lastPage, pages) => lastPage.nextCursor || undefined
});
Uses the useInfiniteQuery hook to fetch projects data and manage pagination and fetching state.
useEffect(() => {
  const handleScroll = () => {
    if (window.innerHeight + document.documentElement.scrollTop !== document.documentElement.offsetHeight || isFetchingNextPage) return;
    fetchNextPage();
  };
  window.addEventListener('scroll', handleScroll);
  return () => window.removeEventListener('scroll', handleScroll);
}, [fetchNextPage, isFetchingNextPage]);
Sets up an effect to handle the infinite scroll by listening to the scroll event and fetching the next page only if the user has scrolled to the bottom of the page and if the next page is not already being fetched.