Categories
JavaScript Answers React Native Answers

How to fix slow performance when rendering 100+ items in a React Native FlatList?

Spread the love

Sometimes, we want to fix slow performance when rendering 100+ items in a React Native FlatList.

In this article, we’ll look at how to fix slow performance when rendering 100+ items in a React Native FlatList.

How to fix slow performance when rendering 100+ items in a React Native FlatList?

To fix slow performance when rendering 100+ items in a React Native FlatList, we can set the initialNumToRender prop to set how many items are rendered the first time.

We can also replace anonymous functions in props with named functions.

For instance, we write:

import * as React from 'react';
import { FlatList, Text, View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';

const flatListItems = Array(200)
  .fill()
  .map((_, i) => ({ title: i, id: i }));

const Item = ({ title }) => (
  <View
    style={{
      backgroundColor: '#f9c2ff',
      padding: 20,
      marginVertical: 8,
      marginHorizontal: 16,
    }}>
    <Text>{title}</Text>
  </View>
);

export default function App() {
  const renderItem = ({ item }) => <Item title={item.title} />;
  const keyExtractor = (item) => item.id;

  return (
    <View style={{ height: 300 }}>
      <FlatList
        initialNumToRender={10}
        data={flatListItems}
        renderItem={renderItem}
        keyExtractor={keyExtractor}
      />
    </View>
  );
}

to set renderItem and keyExtractor to named functions.

And we set initialNumToRender to 10 to only render the first 10 items when the FlatList is mounted.

Conclusion

To fix slow performance when rendering 100+ items in a React Native FlatList, we can set the initialNumToRender prop to set how many items are rendered the first time.

We can also replace anonymous functions in props with named functions.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *