Image Pipeline with React Native ListView

February 19, 2017 0 Comments

Image Pipeline with React Native ListView

 

 

In mobile apps, scrolling through a list of images is a very common use case for which users have high expectations. In a previous story, I shared formulas that I used in order to cache images with RN. In this story, I would like to share how ListView can be used to optimize image processing when scrolling through images.

Consider a list of entries like an Instagram feed. We fetch a page from the server. At first, when the user scrolls towards the end of the list, we fetch more entries from the server. Secondly, when an entry enters the viewport, we trigger the image cache to display the image. Finally, when the entry goes outside the viewport, and if the image hasn’t been cached yet, we would like to cancel the request to the image URI in order to prioritize requests for the visible entries.

In the example below, we fetch entries from a firebase backend by pages of ten. When we reach the end of the list, we fetch a new page by using the onEndReached event.

Now we can use onChangeVisibleRows() to only mount images when they are visible. We create a row component with a visible attribute. We use the ref() callback to keep a map up to date of each of the mounted rows. In onChangeVisibleRows(), we update the visible property for each row that becomes visible or invisible.

In the Row component, we can use the visible property to mount/unmount the image according to its visibility. We use the react-native-img-cache package for this.

In the last step, we cancel the HTTP request to download the image if the row becomes invisible. react-native-img-cache relies on react-native-fetch-blob which provides a way to both download image without sending it over the JS bridge and to cancel an HTTP request.

Do you find this guide useful? I’m looking forward to reading your feedback.


Tag cloud