React Native: ScrollView vs. FlatList vs. SectionList
React Native: ScrollView vs. FlatList
React Native is a popular framework for building mobile apps using JavaScript and React. When displaying lists of data, you have a few options, but two of the most common components are ScrollView
and FlatList
.
The TLDR:
- Use
ScrollView
if you have a small, static list of items. It's simple and easy to use but can become inefficient with large datasets. - Use
FlatList
if you have a large list of data. It provides better performance and additional features that help manage large datasets effectively.
I'll share some examples and differences below:
ScrollView
ScrollView
is a basic component used to create a scrollable container in React Native. It is best for smaller lists where the total number of items is relatively small. This is because ScrollView
renders all its child components at once, which can be inefficient for long lists.
Example:
import React from 'react'; import { ScrollView, Text, StyleSheet } from 'react-native'; const ScrollViewExample = () => { return ( <ScrollView style={styles.container}> {Array.from({ length: 20 }, (_, i) => ( <Text key={i} style={styles.item}>Item {i + 1}</Text> ))} </ScrollView> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 20, }, item: { marginVertical: 10, fontSize: 18, }, }); export default ScrollViewExample;
When to use it?
- Small lists with a limited number of items.
- Static content where performance is not a concern.
- Simple scrollable views with relatively few children.
FlatList
FlatList
is designed for efficiently rendering large lists. It only renders items that are currently visible on the screen, which helps keep performance optimal even with large datasets. FlatList
also includes handy features like item separators, pull-to-refresh, and infinite scrolling.
Example:
import React from 'react'; import { FlatList, Text, StyleSheet } from 'react-native'; const data = Array.from({ length: 100 }, (_, i) => ({ key: `Item ${i + 1}` })); const FlatListExample = () => { return ( <FlatList data={data} renderItem={({ item }) => <Text style={styles.item}>{item.key}</Text>} keyExtractor={item => item.key} style={styles.container} /> ); }; const styles = StyleSheet.create({ container: { flex: 1, padding: 20, }, item: { marginVertical: 10, fontSize: 18, }, }); export default FlatListExample;
When to use it?
- Large lists with many items.
- Lists that require efficient rendering to maintain performance.
- When you need extra features like separators, headers, or footers.