How to implement Infinite Scrolling in React Native

ghostkeeper10

Rupesh Ghosh

Posted on May 1, 2024

How to implement Infinite Scrolling in React Native

In mobile apps, displaying large datasets efficiently is crucial. Imagine a social media feed or an e-commerce product listing, you don't want to overwhelm the user by loading everything at once. Infinite scrolling, where new content loads as the user scrolls down, provides a smooth and performant solution.

Setting up the project

For this blog post, we will assume you have a React Native project set up and an API endpoint that returns paginated data.

Install react-query

npm install react-query
Enter fullscreen mode Exit fullscreen mode

React Query provides useInfiniteQuery hook which is specifically designed for fetching and managing paginated data. You can read more about useInfiniteQuery here

Implementing Infinite Scrolling with useInfiniteQuery

  • Define the Query Function

This function fetches data from the API endpoint. It should accept the current page number as a parameter and return the fetched data.

const fetchArticles = async (page = 1: number) => {
  const response = await fetch(`http://api.example.com?page=${page}`);
  return response.json();
}
Enter fullscreen mode Exit fullscreen mode
  • Using useInfiniteQuery
import { useInfiniteQuery } from 'react-query';

const ArticleList = () => {
  const { 
    data, 
    isLoading, 
    fetchNextPage, 
    hasNextPage
  } = useInfiniteQuery('articles', fetchArticles, {
    getNextPageParam: (lastPage) => lastPage.hasNextPage || undefined 
  });

  return (
    <FlatList
      data={data?.pages.flat()}
      renderItem={({ item }) => <Article article={item} /> }
      onEndReached={hasNextPage && fetchNextPage}
      ListFooterComponent={isLoading && ActivityIndicator}
     // other FlatList props
    />
  )
}
Enter fullscreen mode Exit fullscreen mode
  • useInfiniteQuery manages the fetching and caching of paginated data.
  • getNextPageParam is crucial for pagination. It takes the last fetched page (lastPage) and determines the next page parameter for the API request. If there are no more pages, it returns undefined. Modify this function based on your API's pagination structure (e.g., page numbers).
  • isLoading indicates if data is currently being fetched. You can use this to display a loading indicator while data loads. A loading indicator is displayed using ListFooterComponent

  • onEndReached within FlatList gets called when the user scrolls close to the end of the list. It's used to trigger the loading of the next page of data.

  • We can also adjust the threshold for triggering onEndReached using the onEndReachedThreshold prop of FlatList. This value represents a fraction of the list's viewable height from the bottom For example 0.5 means triggering when the user is halfway through the last visible item.

Conclusion

By leveraging useInfiniteQuery, you can effortlessly implement infinite scrolling in your React Native applications. This approach goes beyond articles – you can adapt it to various use cases like product listings, chat history, or any scenario where you're dealing with large datasets.

💖 💪 🙅 🚩
ghostkeeper10
Rupesh Ghosh

Posted on May 1, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related