Blog>
Snippets

Implementing Infinite Scroll

Show how to implement an infinite scroll feature in a React Native app using the useInfiniteQuery hook to fetch and display a list of items as the user scrolls.
import React from 'react';
import { FlatList, ActivityIndicator, Text } from 'react-native';
import { useInfiniteQuery } from 'react-query';

const fetchPosts = async ({ pageParam = 1 }) => {
  const response = await fetch(`https://your.api/posts?page=${pageParam}`);
  return response.json();
};
Defines the fetchPosts function to fetch posts from an API with pagination support. Uses the useInfiniteQuery hook from React Query for data fetching.
const PostsInfiniteScroll = () => {
  const { data, isLoading, fetchNextPage, hasNextPage } = useInfiniteQuery('posts', fetchPosts, {
    getNextPageParam: (lastPage, allPages) => lastPage.nextPage ?? false
  });

  const renderPost = ({ item }) => (<Text>{item.title}</Text>);

  if (isLoading) return <ActivityIndicator />;

  return (
    <FlatList
      data={data.pages.flatMap(page => page.results)}
      renderItem={renderPost}
      keyExtractor={(item, index) => item.id.toString()}
      onEndReached={() => hasNextPage && fetchNextPage()}
      onEndReachedThreshold={0.5}
    />
  );
};
This component uses the useInfiniteQuery hook to fetch posts and display them with a FlatList. It implements infinite scrolling by fetching the next page of posts when the user scrolls to the end.
export default PostsInfiniteScroll;
Exports the PostsInfiniteScroll component for use in the application.