import React, { useCallback } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
const ITEM_HEIGHT = 50;
const data = Array.from({ length: 1000 }, (_, i) => ({ id: String(i + 1), title: `Item ${i + 1}` }));
export default function OptimizedFlatList() {
const renderItem = useCallback(({ item }) => {
return <Text style={styles.item}>{item.title}</Text>;
}, []);
const getItemLayout = (_data, index) => ({ length: ITEM_HEIGHT, offset: ITEM_HEIGHT * index, index });
return (
<View style={styles.container}>
<FlatList
data={data}
renderItem={renderItem}
keyExtractor={item => item.id}
initialNumToRender={10}
getItemLayout={getItemLayout}
removeClippedSubviews={true}
/>
</View>
);
}
const styles = StyleSheet.create({
container: { flex: 1, paddingTop: 40 },
item: { height: ITEM_HEIGHT, paddingHorizontal: 15, justifyContent: 'center', borderBottomWidth: 1, borderColor: '#ccc' },
});We created a constant ITEM_HEIGHT to define the height of each item. This helps getItemLayout calculate the position of each item, which improves scroll performance by avoiding measurement on the fly.
We used useCallback to memoize the renderItem function, preventing unnecessary re-renders.
Setting initialNumToRender to 10 limits how many items render initially, speeding up the first load.
removeClippedSubviews frees memory by unmounting items outside the viewport.
These combined optimizations make the FlatList smooth and efficient even with 1000 items.