Raul
Raul

Reputation: 3081

React Native FlatList key

I have a FlatList which renders a custom component "Card". I am passing as keyExtractor this function:

const keyExtractor = (item) => item.id;

And my renderItem function looks like this:

const renderItem = ({item, index}) => <Card {...item} />

My question is: should I pass a key to the Card component? I mean, should I do this

const renderItem = ({item, index}) => <Card key={item.id} {...item} />

to avoid my flatlist re-render components and improve the performance of my list? I have seen some people doing this... but I have never done it. If the answer is yes, why we need keyExtractor if each rendered component have a key?

Of course, if I pass a key to my custom component I will do this on its implementation:

return <View key={props.key}>...</View>

Thank you.

Upvotes: 0

Views: 763

Answers (1)

MoKhajavi75
MoKhajavi75

Reputation: 2702

You should have a unique property in your data and use it as a key. There is no need to pass the key to your Card component.

If your data is something like this:

data = [
  {
    id: 'a12f56e5',
    name: 'me',
    age: 24
  }
  // ...
];

then you can use id as key.

Also, please take a look at this to improve your FlatList performance

Upvotes: 2

Related Questions