List optimization
- React Native course
- Expert
- Lesson 10/47
- 5 min
Learn FlatList and SectionList optimization.
List optimization
In React Native, long lists are rendered with FlatList or SectionList. Misuse re-renders the whole list on every scroll and freezes the UI. Proper use renders only the on-screen items (virtualization).
Key settings: keyExtractor, getItemLayout, windowSize, removeClippedSubviews. If the list item is wrapped in memo, only the changed item renders.
getItemLayout
getItemLayout lets FlatList know an item's position without measuring. With fixed-height items, scrolling gets faster and jump-to-index becomes possible.
Its signature is (data, index) => ({ length, offset, index }). If the item height is variable, getItemLayout cannot be used; FlatList must measure then.
Practice Optimize the FlatList
Write a FlatList component. Set data to items, keyExtractor to return each item's id, and renderItem to show a Text. Import FlatList from react-native.
Starter code
import React from 'react';
// Import FlatList and Text from react-native
// Write the FlatList component
export default function App() {
return null;
}Sample solution
import React from 'react';
import { FlatList, Text } from 'react-native';
const items = [{ id: '1', title: 'One' }];
export default function App() {
return (
<FlatList
data={items}
keyExtractor={item => item.id}
renderItem={({ item }) => <Text>{item.title}</Text>}
/>
);
}Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does keyExtractor do in FlatList?
- Gives a unique key
- Loads images Correct answer
- Picks colors
- Formats dates
Explanation: keyExtractor gives each item a unique key.
2 Write the FlatList prop name
<FlatList
data={items}
____={item => item.id}
renderItem={renderItem}
/>
<FlatList
data={items}
keyExtractor={item => item.id}
renderItem={renderItem}
/>
Explanation: keyExtractor identifies items.
3 Match the FlatList settings
| Term | Meaning |
|---|---|
keyExtractor |
Unique key |
getItemLayout |
Fixed height |
windowSize |
Render window |
removeClippedSubviews |
Removes offscreen |