Optimize React Native Mobile App Performance Using FlatList

Optimize React Native Mobile App Performance Using FlatList

The introduction of React Native by Facebook now Meta completely revolutionized the workflow of mobile app development for many software engineers. With a large community of JavaScript developers supporting this framework, it is not surprising how quickly it rose to popularity over the years.

React Native allows developers to build cross-platform applications from one codebase, this practically means that you can develop a mobile app that works on iOS and Andriod phones without the need to manage two codebases written in different languages, in this case, Swift for iOS and Kotlin or Java for Andriod.

You might be wondering, how performant are these apps built in React Native? since they are not technically written in the native programming languages for these two operating systems.

When you code in React Native, the JavaScript engine communicates with the native code and renders your application using native components from the native programming languages (Kotlin or Swift).

So in reality, your apps are still written in these languages but just in a different way, hence React Native apps have near or equivalent level of performance as applications written in either Kotlin or Swift.

We have all seen and used popular apps like Instagram, Pinterest, and even our everyday e-commerce applications and they all have one thing in common.

Can you take a quick guess?

A list of related Items, these could be product listings on an e-commerce website, a list of news articles, or social media posts like you see on Instagram. Lists can be generated from a small dataset, resulting in a concise list that may contain anywhere from 1 to 50 items, and lists could also be generated from a large dataset resulting in a longer list that could range from 1 to 20,000. Data displayed on popular apps like Instagram falls into the category of large datasets

Displaying a list of 20,000 posts or products on an app is equivalent to opening a narrow door to a bank vault to 20,000 people at the same time. Think about it: what do you think would happen? There is going to be a stampede, and people could even die in the process. Not to paint a gory picture, but this could be a reality. If you compare this scenario to a mobile app, this is the exact representation of what would happen to your application if you decide to load a large dataset of lists at the same time. Your app is going to turn out slow, and in the worst-case scenario, your app will crash.

React Native was developed to combat this situation to ensure that developers build performant applications that lead to improved user experience. FlatList is a React Native component that is commonly used to render large datasets without affecting the application’s overall performance.

In this article, we will explore how the FlatList component works, along with real-life examples of when it is used. By the end of this article, you should be able to:

  • Display a dataset with FlatList.

  • Identify the difference between using ScrollView and FlatList to display a dataset.

  • Understand the benefits of using FlatList for performance and user experience.

  • Recognize real-world use cases for the FlatList component.

Rendering Large datasets with ScrollView

ScrollView is a core React native component that allows you to scroll through content vertically and horizontally, It acts as a scrollable container for your application when the content goes beyond the user’s viewport, you can think of this as a scrollable div.

It is the recommended component for enabling scrolling in your application. Without the FlatList component, users would not be able to scroll through your app effectively.

This seems like a good approach to follow when rendering a list from a small dataset, but not so much when the list is coming from a large dataset, let’s explore this fact.

Recall earlier in the article, when we mentioned displaying product listings on an e-commerce website or user posts on social media apps like Instagram, these are examples of lists generated from a large dataset.

How would you typically display items from a dataset?

It is common knowledge among React developers that displaying items in JSX can be achieved using the map method, this can also be done in React native as shown below;

import { StyleSheet, View, Text, SafeAreaView } from 'react-native';

const data = [
  { petName: 'Fiftys', key: 1 },
  { petName: 'Trimp', key: 3 },
  { petName: 'Bubble', key: 4 },
  { petName: 'Paris', key: 5 },
  { petName: 'Samson', key: 6 },
  { petName: 'Chloe', key: 7 },
  { petName: 'Sara', key: 8 },
  { petName: 'Bowi', key: 9 },
  { petName: 'Fran', key: 10 },
  { petName: 'Lucky', key: 11 },
  { petName: 'Jerome', key: 12 },
  { petName: 'Bowi', key: 13 },
  { petName: 'Fran', key: 14 },
  { petName: 'Lucky', key: 15 },
  { petName: 'Jerome', key: 16 },
  { petName: 'Bowi', key: 17 },
  { petName: 'Fran', key: 18 },
  { petName: 'Lucky', key: 19 },
  { petName: 'Jerome', key: 20 },
  { petName: 'Bowi', key: 21 },
  { petName: 'Fran', key: 22 },
  { petName: 'Lucky', key: 23 },
  { petName: 'Jerome', key: 24 },
  { petName: 'Bowi', key: 25 },
  { petName: 'Fran', key: 26 },
  { petName: 'Lucky', key: 27 },
  { petName: 'Jerome', key: 28 },
  { petName: 'Bowi', key: 29 },
  { petName: 'Fran', key: 30 },
  { petName: 'Lucky', key: 31 },
  { petName: 'Jerome', key: 32 },
  { petName: 'Bowi', key: 33 },
  { petName: 'Fran', key: 34 },
  { petName: 'Lucky', key: 35 },
  { petName: 'Jerome', key: 36 }
]

export default function HomeScreen() {
  return (
    <SafeAreaView style={styles.mainContainer}>
        <View style={styles.container}>
          {data.map((item) => {
            return (
              <View key={item.key}>
                <Text style={styles.paragraph} >Pet name: {item.petName}</Text>
              </View>)
          })}
        </View>
    </SafeAreaView>
  );
}

This is the method many of us React developers are familiar with, displaying our data with the map method, this will work excellently on a React web application, whereas with React Native we will most definitely encounter a problem. Let’s take a look;

Notice that the code that displays the interface above does not contain the ScrollView component, so if you copy this code to your code editor and run it on your device or simulator, you will be unable to scroll to see the full list of pets, now let’s wrap the list around a ScrollView component.

First, you need to import ScrollView from React Native.

import { StyleSheet, View, Text, ScrollView, SafeAreaView } from 'react-native';

export default function HomeScreen() {
  return (
    <SafeAreaView style={styles.mainContainer}>
      <ScrollView>
        <View style={styles.container}>
          {data.map((item) => {
            return (
              <View key={item.key}>
                <Text style={styles.paragraph} >Pet name: {item.petName}</Text>
              </View>)
          })}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

If you run this code your list should be scrollable as shown below;

This is perfect, but is not a recommended way to render a list especially when the dataset is large. If this data was anything from 1 to 500 and above, it would lead to:

  • Increase memory consumption

  • Lagging scrolling

  • Slow loading times

This is because ScrollView renders all the items from the dataset at the same time, if you have 10,000 items in your dataset, once the user logs onto your app; the 10,000 items will load and be displayed at the same time, and this is not ideal.

Let us see this in real-time, we will not be rendering 10,000 items with ScrollView component because this action might crash your application, but I am going to show you how this would work under the hood.

export default function HomeScreen() {
  return (
    <SafeAreaView style={styles.mainContainer}>
      <ScrollView>
        <View style={styles.container}>
          {data.map((item) => {
            console.log(item.key)
            return (
              <View key={item.key}>
                <Text style={styles.paragraph} >Pet name: {item.petName}</Text>
              </View>)
          })}
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

In your code, add a console.log( ) to your code as shown above to log the key of each item. The total number of items from the dataset has been increased to 322 so you should see 322 items logged at the same in your console.

This would be a recipe for disaster in an actual application that would be used by millions of users. Now let’s see how FlatList helps to combat this drawback.

Rendering a Large Dataset with FlatList

When you use FlatList to display a list of items, you do not need to use the ScrollView component, the FlatList comes automatically with the ability to scroll when the content goes beyond the user’s viewport.

Now, that we have seen how to render a list of data with the ScrollView Component, let’s go ahead and render the same data with FlatList.

  • Import FlatList from React Native

  • Replace the previous code containing the ScrollView with the FlatList component.

    FlatList takes two compulsory props:

    • data: this is the information or the list of data to be rendered in your application.

    • renderItem: this is a callback function that returns the JSX of the list of it.

Discover all the props available with the FlatList component here .

import { View, SafeAreaView, FlatList } from 'react-native';

export default function HomeScreen() {
  return (
    <SafeAreaView style={styles.mainContainer}>
        <View style={styles.container}>
          <FlatList 
            data={data}
            renderItem={({item})=>{
              return(
                <Text style={styles.paragraph}>Pet name: {item.petName}</Text>
              </View>
              )
            }}
          />
        </View>
    </SafeAreaView>
  );
}

Now let’s output to our console the list of items that are initially rendered by FlatList.

From the clip above, notice that the FlatList renders 196 items first from a total of 322 items, if you are viewing this on a smaller device, you will see less than 196 items, but FlatList ensures that it renders enough items for devices of different sizes, certainly a larger device like an iPad would be able to contain about 196 items at first display.

As you scroll down, you will notice that the number of items shown in your console increases, this means that FlatList loads and displays items from your dataset only when they are in the user’s view, unlike the ScrollView component that loads all the data at the same time, which is great for excellent app performance and user experience.

If you had to display 10,000 items, what would you opt for, a FlatList or ScrollView component?

The Benefits of using the FlatList Component

FlatList can accomplish everything that a ScrollView does more efficiently. It offers a variety of props that make rendering large datasets less expensive and customizable. Let’s go over some of the benefits FlatList offers as a single component:

  • Lazy Loading: this is one of those situations where lazy is not considered a bad concept. Lazy loading speeds up web pages or application load times by only rendering required content first and waits to load other contents of the app when the user or the browser needs it. This is exactly what the FlatList does and is very beneficial in situations like displaying a long catalog of product images, loading all the images at the same time, will cause your application to run slower than it should.

  • Infinite Scroll: FlatList allows you to load more items as you scroll down your app, without the need to append a button like ‘Click to see more’. Real-life evidence of this is on your social media apps like X and Instagram, the more you scroll through the page the more items are rendered, it’s like walking down an endless street with new houses appearing in front of you.

  • Pull to Refresh: You are probably familiar with this functionality in most social media apps, it is a touch screen functionality that lets you swipe down at your screen to load new content. FlatList comes out of the box with the onRefresh and refreshing prop that will enable you to achieve this feature easily.

  • Scroll to Index Support: FlatList lets you programmatically scroll to a specific item in your dataset using its index. A real-life example of this is in an e-commerce app, when you click on a button labeled "Dresses", the app automatically scrolls to the section displaying dress products. This makes it easy for users to jump straight to the content they're interested in without manual scrolling.

Real World Usecases of FlatList

  • Scrolling through a product catalog in e-commerce apps.

  • Displaying a continuous scrolling feed of posts, images, and videos from users on social media.

  • Showing a list of chat messages in a conversation thread.

  • News feeds and infinite scrolling for content-heavy applications.

  • Presenting a collection of images in a gallery.

  • An address book or contact management app where users can scroll through their saved contacts.

  • An event scheduling app where users can scroll through the schedule of talks, sessions, and activities.

These and many more are real-life examples of when you can recognize the usage of FlatLists in an application or applications you could develop with the use of FlatList for better performance and user experience.

Conclusion

And that’s a wrap! In this article, we introduced the React Native framework and how it has revolutionized the mobile app development landscape. We also explored two methods for displaying lists of data in your application: the ScrollView method and the FlatList method. While both can be used, the FlatList method is highly recommended, especially when dealing with large datasets.

Being a better developer means creating applications that satisfy users and enhance their experience. Using the FlatList component not only improves your app's performance and speed but also encourages user engagement, ultimately boosting customer retention and revenue.

Ready to take your app development skills to the next level? Start implementing FlatList in your projects today and see the difference it makes! Happy coding!