Blog>
Snippets

Initializing React Environment for Infinite Scroll

Show how to set up a new React project, install TanStack Virtual and React-Query, and prepare the environment for infinite scroll implementation.
npx create-react-app my-app
cd my-app
Creating a new React project named 'my-app' and navigating into the project directory.
npm install @tanstack/react-query @tanstack/react-virtual react-intersection-observer axios
Installing necessary packages for infinite scroll: React Query for data fetching, TanStack Virtual for virtualization, React Intersection Observer for detecting when an element is in view, and Axios for making HTTP requests.
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your app's components will go here */}
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}

export default App;
Setting up React Query with a QueryClient and wrapping the application's components with QueryClientProvider for enabling React Query features throughout the app. ReactQueryDevtools is also included for debugging purposes.
import { useInfiniteQuery } from '@tanstack/react-query';
import axios from 'axios';

const fetchProjects = ({ pageParam = 1 }) => axios.get(`/api/projects?page=${pageParam}`).then(res => res.data);

const useProjectsInfiniteQuery = () => useInfiniteQuery(['projects'], fetchProjects, {
  getNextPageParam: (lastPage, allPages) => lastPage.nextPage,
});
Defining a custom hook for fetching data with pagination using React Query's useInfiniteQuery hook. This example fetches projects from an API, automatically handles pagination with `getNextPageParam`.
import { useVirtualizer } from '@tanstack/react-virtual';
import React, { useRef } from 'react';

const VirtualizedList = ({ data }) => {
  const parentRef = useRef(null);
  const rowVirtualizer = useVirtualizer({
    count: data.length,
    getScrollElement: () => parentRef.current,
  });

  return (
    <div ref={parentRef} style={{ overflow: 'auto', height: '100vh' }}>
      {rowVirtualizer.virtualItems.map((virtualRow) => (
        <div key={virtualRow.index} style={{ height: virtualRow.size }}>
          {data[virtualRow.index].name}
        </div>
      ))}
    </div>
  );
};
Implementing a virtualized list using TanStack Virtual. This component takes an array of data and uses a React ref as a scroll container to virtualize the list items, improving performance by rendering only visible items.