In this lesson, you will learn how to build a seamless "Load-More" pagination experience so your app can fetch and display large datasets incrementally as the user scrolls.
The Concept of Infinite Scrolling
Instead of downloading 1,000 items at once—which would crash your app or drain the user's data—you fetch items in small chunks. When the user reaches the bottom of your FlatList, you trigger a function to fetch the "next page" of data, append it to your existing list, and update the view.
Using onEndReached
The FlatList component has a built-in prop called onEndReached. This prop accepts a function that fires automatically when the scroll position reaches the end of the list.
To prevent the fetch function from triggering multiple times while the user is already scrolling, we use the onEndReachedThreshold prop. This defines how far from the bottom (e.g., 0.5 for halfway, 0.1 for 10% from the bottom) the trigger should activate.
Here is how you wire it up:
const [data, setData] = useState([]);
const [page, setPage] = useState(1);
const fetchMoreData = () => {
// Logic to fetch the next page from your API
const nextPage = page + 1;
// Append new items to your existing data array
setData((prevData) => [...prevData, ...newItems]);
setPage(nextPage);
};
<FlatList
data={data}
renderItem={({ item }) => <Text>{item.title}</Text>}
onEndReached={fetchMoreData}
onEndReachedThreshold={0.2} // Triggers when 20% from the bottom
/>
Pro-Tip: The Loading Indicator
Because fetching data takes time, it is best practice to include a ListFooterComponent. When you are in the middle of a network request, you can display a simple ActivityIndicator at the bottom of the list. This tells the user, "Hold on, more content is arriving," keeping the interface feeling snappy and responsive.
Key Takeaway: Use onEndReached combined with onEndReachedThreshold to create an infinite scroll experience that fetches data in small, manageable chunks.