![Koda School](/_next/image?url=%2Fimages%2Flogo.png&w=96&q=75)
KodaSchool
Learn To Code
Using FlatList for Efficient List Rendering in React Native
When developing mobile applications, it's common to need to display lists of data. In React Native, the FlatList component is the go-to solution for rendering large lists efficiently.
topics
When developing mobile applications, it's common to need to display lists of data. In React Native, the FlatList
component is the go-to solution for rendering large lists efficiently. In this article, we'll explore how to use FlatList
, its key features, and best practices for optimal performance.
Why Use FlatList?
FlatList
is designed to render large lists of data efficiently. It only renders items that are currently visible on the screen, which significantly improves performance and memory usage, especially for long lists.
Key benefits of FlatList
:
- Efficient memory usage
- Optimized performance for large lists
- Built-in scrolling and pull-to-refresh capabilities
- Easy implementation of infinite scrolling
Basic Usage of FlatList
Let's start with a basic example of how to use FlatList
:
import React from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
const data = [
{ id: '1', title: 'Item 1' },
{ id: '2', title: 'Item 2' },
{ id: '3', title: 'Item 3' },
// ... more items
];
const Item = ({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
);
const BasicFlatList = () => {
const renderItem = ({ item }) => (
<Item title={item.title} />
);
return (
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={item => item.id}
/>
);
};
const styles = StyleSheet.create({
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
});
export default BasicFlatList;
In this example:
- We define a
data
array containing the items to be rendered. - We create an
Item
component to render each item in the list. - We use
FlatList
to render the list, providing thedata
,renderItem
, andkeyExtractor
props.
Key Props of FlatList
data
: An array of data to be rendered in the list.renderItem
: A function that returns the component to render for each item.keyExtractor
: A function to extract a unique key for each item.
Advanced FlatList Features
Pull-to-Refresh
Implement pull-to-refresh functionality:
const [refreshing, setRefreshing] = useState(false);
const onRefresh = React.useCallback(() => {
setRefreshing(true);
fetchData().then(() => setRefreshing(false));
}, []);
<FlatList
// ... other props
refreshing={refreshing}
onRefresh={onRefresh}
/>
Infinite Scrolling
Load more data as the user scrolls:
const [data, setData] = useState([]);
const [loading, setLoading] = useState(false);
const fetchMoreData = () => {
if (loading) return;
setLoading(true);
fetchData().then(newData => {
setData([...data, ...newData]);
setLoading(false);
});
};
<FlatList
// ... other props
onEndReached={fetchMoreData}
onEndReachedThreshold={0.5}
ListFooterComponent={() => loading ? <ActivityIndicator /> : null}
/>
Section Lists
For grouped data, use SectionList
instead:
import { SectionList } from 'react-native';
const DATA = [
{
title: 'Main dishes',
data: ['Pizza', 'Burger', 'Risotto'],
},
{
title: 'Sides',
data: ['French Fries', 'Onion Rings', 'Fried Shrimps'],
},
// ... more sections
];
const MySectionList = () => (
<SectionList
sections={DATA}
keyExtractor={(item, index) => item + index}
renderItem={({ item }) => (
<View style={styles.item}>
<Text style={styles.title}>{item}</Text>
</View>
)}
renderSectionHeader={({ section: { title } }) => (
<Text style={styles.header}>{title}</Text>
)}
/>
);
Performance Optimization
- Use
getItemLayout
: If your items have a fixed height, providegetItemLayout
to optimize rendering:
getItemLayout={(data, index) => (
{length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index}
)}
- Implement
windowSize
: Control how many items are rendered outside of the visible area:
<FlatList
// ... other props
windowSize={21} // Default is 21
/>
- Use
removeClippedSubviews
: On Android, use this prop to unmount components that are outside of the viewport:
<FlatList
// ... other props
removeClippedSubviews={Platform.OS === 'android'}
/>
- Optimize your
renderItem
function: Memoize therenderItem
function to prevent unnecessary re-renders:
const renderItem = React.useCallback(({ item }) => (
<Item title={item.title} />
), []);
- Use
PureComponent
orReact.memo
for list items: This ensures that items only re-render when their props change:
const Item = React.memo(({ title }) => (
<View style={styles.item}>
<Text style={styles.title}>{title}</Text>
</View>
));
Best Practices
- Always use the
keyExtractor
prop or ensure your data has a uniquekey
property. - Avoid using
index
as a key unless your list is static and will not change. - Keep your
renderItem
function as simple as possible. Complex render functions can impact performance. - If you need to render a large number of items, consider implementing pagination or infinite scrolling.
- Use
FlatList
for long lists and simpleScrollView
for shorter, static lists. - Optimize images in your list by using appropriate sizing and caching mechanisms.
FlatList
is a powerful tool for rendering efficient, scrollable lists in React Native. By understanding its features and following best practices, you can create smooth, performant list experiences in your mobile applications. Remember to always test your lists with large datasets and on various devices to ensure optimal performance across different scenarios.
share
As a Fullstack Software Engineer, I design and develop user-centric and robust systems and applications using HTML, CSS, Bootstrap, React Js, React Native, and Kotlin(Android).