techStackGuru

React Native FlatList


The FlatList component renders scrollable lists efficiently, especially for large datasets. You can customize the style, behavior, and performance by adding props such as data, renderItem, keyExtractor, etc. Using ListFooterComponent and initialNumToRender techniques will help you render smoother and consume less memory.

Example

import React, { useState } from 'react';
import { View, FlatList, Text } from 'react-native';

const MyFlatList = () => {
  const [data, setData] = useState([
    { id: '1', title: 'Item 1' },
    { id: '2', title: 'Item 2' },
    { id: '3', title: 'Item 3' },
    { id: '4', title: 'Item 4' },
    { id: '5', title: 'Item 5' },
  ]);

  const renderItem = ({ item }) => (
    <View style={{ padding: 10, borderBottomWidth: 1, borderBottomColor: '#ccc' }}>
      <Text>{item.title}</Text>
    </View>
  );

  return (
    <FlatList
      data={data}
      renderItem={renderItem}
      keyExtractor={item => item.id}
    />
  );
};

export default MyFlatList;
Output
react-native-flatlist

As part of our state variable, we maintain an array containing the items titles and ids. In the renderItem function, we pass an item and return the JSX to render. Data is passed as the source of items, renderItem renders each item, and keyExtractor extracts a unique key for each item.

  • data: The data array to render.
  • renderItem: The function to render each item.
  • keyExtractor: Generates unique keys for each item, essential for performance.
  • style: Styles the FlatList itself.
  • contentContainerStyle: Additional styles for the content container (inner scrollable area).
  • initialNumToRender: Renders only a few initial items for better UX and performance.
  • ListFooterComponent: Displays a loading indicator for large lists.
  • Example 2

    import React from 'react';
    import { View, Text } from 'react-native';
    import YourComponent from './YourComponent';
    
    const data = [
      // Your data array
    ];
    
    const renderItem = ({ item }) => (
      <View style={styles.listItemContainer}>
        <Image source={{ uri: item.imageUrl }} style={styles.itemImage} />
        <Text style={styles.itemText}>{item.text}</Text>
      </View>
    );
    
    const ListFooterComponent = () => (
      <View style={styles.footerContainer}>
        <Text style={styles.footerText}>End of List</Text>
      </View>
    );
    
    const YourScreen = () => {
      return (
        <YourComponent
          data={data}
          renderItem={renderItem}
          keyExtractor={(item) => item.id.toString()} // Assuming id is a unique identifier for each item
          style={styles.container}
          contentContainerStyle={styles.contentContainer}
          initialNumToRender={10} // Example value
          ListFooterComponent={ListFooterComponent}
        />
      );
    };
    
    export default YourScreen;