Flatlist Over ArrayPrototype.map
Chinaza Adimoha
Senior Frontend Developer | Typescript | ReactJS Developer | Next JS && SSR | Fintech | Banking(Core Banking) | HealthTech (EHR) | Real Estate Tech | Creating Responsive High Performance Software Products |
In my Journey of learning and building mobile applications, using React Native and Expo, I have learned a great deal about why certain native components behave in certain ways.
Why would I prefer rendering a List or an array of items using the Flatlist native component? as to making use of your traditional Array method (map)?
The best practice is to make use of the FlatList component. This native component dynamically handles the key property that would normally be used in our classic React app
import { View, FlatList, Text, StyleSheet } from "react-native";
import { StatusBar } from "expo-status-bar";
const expenseList = [
{
id: 1,
expense: "car"
},
{
id: 2,
expense: "laptop"
},
];
//render items using the traditional map method
const displayScreen = () => {
return (
<>
{
expenseList.map((item) = {
key={item.id}
return(
<View style={styles.expenseListContainer}>
<Text style={styles.textField}>{item.expense}</Text>
</View>
)
})
}
</>
)
};
//render items using the native Flatlist component
const displayScreen = () => {
return (
<>
<Flatlist
data={expenseList}
renderItem={(itemData) => {
return (
<View style={styles.expenseListContainer}>
<Text style={styles.textField}>
{itemData.item.expense}</Text>
</View>
)
}}
keyExtractor={(item, index) => item.id}
/>
<StatusBar style="auto" />
</>
)
};
const styles = StyleSheet.create({
expenseListContainer: {
flex: 1,
backgroundColor: '#fff',
padding: 50,
paddingHorizontal: 16,
},
textField: {
borderWidth: 2,
borderColor: "#fff1ea",
width: "70%",
marginRight: 8,
padding: 8,
},
});
If you noticed, in the illustration that makes use of the map method, the key is being passed as a key-value pair, where the "id" differentiates each object in the expenseList array when looped through, this takes note of unique values on every render. However, react native would not take cognizance of the key while using the map method.
It is however best practice to make use of the FlatList native component, as it has its own key unique property, called KeyExtractor. React native significantly acknowledges this property.
领英推荐
Another upside to using FlatList component is that it can lazy load items and serve to the user when requested, creating a seamless user experience.
React native is indeed a powerful mobile tool for building unique, complex, dynamic, and beautiful mobile applications.
Feel free to engage this article, and let me know your thoughts in the comment section.
#reactnative #react #javascript #expo
Product Engineer (React, NextJS, Python, Node, AWS)
1 年Very informative, thanks for sharing