Cross Platform

React Native FlatList Example: Best Practices

Pinterest LinkedIn Tumblr

Looking for the best practices for React Native FlatList? Look no further! This article provides you with all the information you need to make your app run smoothly.

FlatList is a powerful React Native component that allows developers to render large sets of data in an efficient and performant way. However, it can also be challenging to use correctly. In this article, we’ll explore best practices for using FlatList in your React Native app and provide you with helpful examples along the way.

Introduction to React Native FlatList.

React Native FlatList is a widely used component that provides an efficient way to render lists in mobile applications. It supports scrolling and lazy loading for large data sets, providing a seamless user experience. With FlatList, developers can display dynamic content efficiently without compromising performance. In this article, we will cover the basics of FlatList and provide best practices for using it in your React Native applications.

How to create Item View

Now let’s move to IDE, and create a new React Native project. As per our feature image will going to create a FlatList render item view that contains actor name, birthplace along with image, So let’s start. Create an ActorItem.tsx file in component directory, and add the below code.

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

export interface Actor {
  id: number,
  name: string,
  bornAt: string,
  photo: string,
}

function ActorItem(props: Actor) {
  const {name, bornAt, photo} = props;
  return (
    <View style={styles.container}>
      <Image style={styles.photo} source={{uri: photo}}/>
      <View style={styles.profileContainer}>
        <Text style={styles.nameText}>{name}</Text>
        <Text style={styles.bornAtText}>{bornAt}</Text>
      </View>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flexDirection: "row",
    shadowColor: 'black',
    shadowOffset: {width: 0, height: 2},
    shadowRadius: 4,
    shadowOpacity: 0.26,
    elevation: 4,
    backgroundColor: '#fff',
    padding: 16,
    marginBottom: 16,
  },
  photo: {
    width: 80,
    height: 80,
    borderRadius: 80 / 2,
    overflow: "hidden",
    borderWidth: 2,
    borderColor: "red"
  },
  profileContainer: {
    flexDirection: "column",
    marginLeft: 16,
  },
  nameText: {
    fontSize: 24,
    fontWeight: "bold"
  },
  bornAtText: {
    fontSize: 18,
  }
});

export default ActorItem

How to use FlatList

Open the App.tsx file or where you wish to use FlatList, and the following code. I have created a function for important all props. That will explain later on this articles in details

<SafeAreaView style={styles.container}>
  <Text style={styles.header}>React Native FlatList Example</Text>
  <View style={styles.listContainer}>
    <FlatList
      data={listItems}
      renderItem={renderItem}
      keyExtractor={keyExtractor}
      alwaysBounceVertical={false}
      getItemLayout={getItemLayout}
    />
  </View>
</SafeAreaView>

Use of keyExtractor prop for efficient rendering.

The keyExtractor prop is a crucial feature of React Native FlatList that helps improve rendering efficiency. It tells the list of which property of each item should be used as its unique identifier. By providing a stable identifier for each item, the FlatList can keep track of which items have changed and which have not, allowing it to efficiently re-render only the items that have been updated. It’s recommended to use a string ID or some other unique identifier for this purpose

  /**
   *  Use keyExtractor prop
   */
  const keyExtractor = useCallback((items: Actor) => items.id.toString(), [])

Implementing the renderItem function for customizing each list item

The renderItem function is where you specify what should be rendered for each item in your FlatList. It should return a component that represents the item, such as a Text component or an Image component.

You can leverage these arguments to build custom UI components for each item based on your specific business logic and design requirements. Remember to keep your render function lean and avoid heavy computations or network requests within it to ensure smooth scrolling and rendering performance.

Note – Avoid arrow functions inline for renderItem

  /**
   *  Avoid arrow functions inline for renderItem
   */
  const renderItem: ListRenderItem<Actor> = useCallback(({item}) => (
    <ActorItem id={item.id} name={item.name} bornAt={item.bornAt} photo={item.photo}/>
  ), []);

Enhance performance by using getItemLayout

Two important props that can help enhance performance in your React Native FlatList are getItemLayout and shouldComponentUpdate. The getItemLayout prop can be used to optimize the rendering of large lists by allowing you to skip the measurement phase for items that are off-screen. This can be a great way to speed up rendering time and improve overall performance. Additionally, the shouldComponentUpdate prop can be used to prevent unnecessary re-rendering of FlatList items that have not been updated. By implementing this prop, you can ensure that only the items that require updating get re-rendered instead of the entire list. Remember, optimizing your code is essential for a smooth user experience, and leveraging these two props is an effective way to start enhancing your app’s performance.

  const ITEM_HEIGHT = 200;
  const getItemLayout = useCallback((data: any, index: number) => ({
    length: ITEM_HEIGHT,
    offset: ITEM_HEIGHT * index,
    index
  }), [])

Finally, your component will be looks like below

Guys, your final FlatList implementation looks like this, You can also download full source at the below of this post,

import {FlatList, ListRenderItem, SafeAreaView, StyleSheet, Text, View} from 'react-native';
import React, {useCallback} from "react";
import ActorItem, {Actor} from "./components/ActorItem";
import {listItems} from "./data/Data";

export default function App() {
  /**
   *  Avoid arrow functions inline for renderItem
   */
  const renderItem: ListRenderItem<Actor> = useCallback(({item}) => (
    <ActorItem id={item.id} name={item.name} bornAt={item.bornAt} photo={item.photo}/>
  ), []);

  /**
   *  Use keyExtractor prop
   */
  const keyExtractor = useCallback((items: Actor) => items.id.toString(), [])

  /**
   * Always use  getItemLayout to optimize FlatList
   */
  const ITEM_HEIGHT = 200;
  const getItemLayout = useCallback((data: any, index: number) => ({
    length: ITEM_HEIGHT,
    offset: ITEM_HEIGHT * index,
    index
  }), [])

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.header}>React Native FlatList Example</Text>
      <View style={styles.listContainer}>
        <FlatList
          data={listItems}
          renderItem={renderItem}
          keyExtractor={keyExtractor}
          alwaysBounceVertical={false}
          getItemLayout={getItemLayout}
        />
      </View>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor:"#eee7e7"
  },
  listContainer: {
    padding: 8,
    flex: 1,
  },
  header: {
    padding: 8,
    fontSize: 24,
    color: "white",
    lineHeight: 48,
    backgroundColor: '#ff0000',
  },
});

Conclusion

That is all about FlatList in React Native, For running the react native project open the terminal and run below script. I hope you enjoy this React Native tutorial,, Follow me on social media to become a better Android Developer.

npm start

Download Source Code

Write A Comment