What's the benefits/advantages of the FlatList Native React-Native component?


(Ben Carp) #1

I’m a react developer, but new to React Native.
Going over the React Native Tutorial, I see there are native React-Native components which are not completely declarative. For example:

        <FlatList
          data={[
            {key: 'Devin'},
            {key: 'Jackson'},
            {key: 'James'},
            {key: 'Joel'},
            {key: 'John'},
            {key: 'Jillian'},
            {key: 'Jimmy'},
            {key: 'Julie'},
          ]}
          renderItem={({item}) => <Text style={styles.item}>{item.key}</Text>}
        />

What advantage does this structure provide over this:

<View>
    {
        [
            {key: 'Devin'},
            {key: 'Jackson'},
            {key: 'James'},
            {key: 'Joel'},
            {key: 'John'},
            {key: 'Jillian'},
            {key: 'Jimmy'},
            {key: 'Julie'},
          ].map( person => <Text style={styles.item}>{person.key}</Text>  )
    }
</View>

(Jed Fox) #2

This structure allows React to only do the processing required to create the JSX as needed, whereas the second example you provided requires the entire list to be iterated over each time you re-render.


(Jose Gomez) #3

FlatList is a Pure Component so it won’t re-render the list if the props don’t change, in the second example it will be re-rendered each time the parent component re-renders. BUT, that isn’t only the reason why, FlatList is a component with a list of callbacks like: OnEndReached, etc, that let you know when the list is already in the last position so you can call your DB for example and load more results like FB, IG does. BUT that isn’t the only reason why, the last reason is optimization, FlatList is a native components which have a lot of optimization so if you are loading 10000x of items inside your list you don’t consume a lot of memory and processing of the phone in your app.