I understand that the FlatList extraData prop is used to re-render components when it changes.
So, imagine this example:
import React from 'react';
import { View, TouchableOpacity, Text, FlatList } from 'react-native';
export default function App() {
const [selectedId, setSelectedId] = React.useState(null);
const items = [
{
id: 'some-unique-id',
title: 'Item 1',
},
];
const renderItem = ({ item }) => {
return (
<SelectableItem
selected={selectedId === item.id}
onPress={() => setSelectedId(item.id)}
/>
);
};
return (
<FlatList
data={items}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId} // works the same if I remove this
/>
);
}
function SelectableItem({ selected, onPress }) {
return (
<TouchableOpacity
style={{ backgroundColor: selected ? 'red' : 'white' }}
onPress={onPress}>
<Text>Click Me!</Text>
</TouchableOpacity>
);
}
I have implemented it thinking in re-render the component when the FlatList state changes...
Test it here.
But, the code works the same if I remove the extra data prop... why?
As the document suggests
By passing extraData to FlatList we make sure FlatList will re-render itself when the state. selected changes. Without setting this prop, FlatList would not know it needs to re-render any items because it is also a PureComponent and the prop comparison will not show any changes.
I think it is because your state is changing the components are updated but in all cases, it's not possible like if you want to change the array and it doesn't affect the state the component will not be updated and the flat list will be the same. We are using an extra data prop to notify the flat list that data has been changed and it should re render.