Load only visible images in Flatlist react native

Viewed 7397

I have made a grid of images using Flatlist. I am loading the images from the web. Currently, all the images are loaded as soon as I navigate to that particular page. What I want is only load those images which are visible on the screen and rest on the scroll. Six images are shown at one time on the screen.

Is it possible to load images on the scroll in Flatlist?

3 Answers

You should be able to do this with the initialNumToRender property on flat list.

so your flatList declaration might be:

<FlatList
    initialNumToRender={2}
    data={[{key: 'a'}, {key: 'b'}]}
    renderItem={({item}) => <Text>{item.key}</Text>}
/>

You can use the Flatlist as below to load only those images which are in the current viewport.

             <FlatList
                    ref={(view) => (this.parentScrollView = view)}
                    data={this.state.data}
                    onScroll={this.handleScroll}
                    keyExtractor={keyExtractor}
                    showsVerticalScrollIndicator={false}
                    bounces={false}
                    numColumns={3}
                    renderItem={this.renderItem}
                    ItemSeparatorComponent={this.ItemSeparatorComponent}
                    ListEmptyComponent={this.ListEmptyComponent}

                    //code for optimization and load only visible items
                    initialNumToRender={8}
                    maxToRenderPerBatch={2}
                    onEndReachedThreshold={0.1}
                    onMomentumScrollBegin={this.onMomentumScrollBegin}
                    onEndReached={this.onEndReached}
           />

My onEndReached is:

onEndReached = () => {
        console.log('end reached');
        if (!this.onEndReachedCalledDuringMomentum) {
            console.log('loading more archived products');
            this.loadMoreProducts();                
            this.onEndReachedCalledDuringMomentum = true;
        }
    }

And onMomentumScrollBegin is:

onMomentumScrollBegin = () => { this.onEndReachedCalledDuringMomentum = false; }

initialNumToRender will mount the first 8 items and will never remove them unless the Flatlist itself doesn't get unmounted. It is helpful to preserve list scrolling performance while fast scrolling the list.

onMomentumScrollBegin and onEndReachedThreshold is used to when to load more element for the list. This could be an API call etc.

Related