Lists are a very common way to represent data in any application. Sometimes this list can be large or may be infinite in some cases like Twitter feeds for example. It is not practical to fetch large data at once. It makes the application slow and it may also happen that the user never interacts with the data at the end of the list.
Pagination helps in solving these problems. Instead of fetching all the data at once, data is fetched in pages, which contain smaller chunks of data. We will see how we can implement pagination in a React Native application using the FlatList
component.
FlatList is used when we want to render a list in a react native application. FlatLists are optimized in a way that only items which are visible on the screen are rendered, unlike ScrollView where all the elements are rendered even if they are not visible on the screen. This reduces memory usage and improves the performance of the application.
To implement pagination we will use these two props of the FlatList:
onEndReachedThreshold
- How far the bottom edge of the list must be from the end of the content in units of the visible length of the list for theonEndReached
callback to be triggered. Therefore, a value of0.5
will triggeronEndReached
when the end of the content is within half the visible length of the list.onEndReached
- This is triggered when the scroll position gets withinonEndReachedThreshold
of the rendered content.
Let us look at the implementation.
For our implementation, we will assume that there is an API that provides 10 items per request along with a next page identifier which will be used to fetch next page data.