I’m working on a React-Native app where I display a list of items using FlatList
. I want to add new items to the list dynamically, but for some reason, the list does not update immediately when I add an item to the array.
import React, { useState } from 'react';
import { View, Text, Button, FlatList } from 'react-native';
export default function App() {
const [data, setData] = useState([{ id: '1', name: 'Item 1' }]);
const addItem = () => {
const newItem = { id: (data.length + 1).toString(), name: `Item ${data.length + 1}` };
setData([...data, newItem]);
};
return (
<View>
<Button title="Add Item" onPress={addItem} />
<FlatList
data={data}
keyExtractor={(item) => item.id}
renderItem={({ item }) => <Text>{item.name}</Text>}
/>
</View>
);
}
When I press the "Add Item" button, I expect the new item to appear immediately in the FlatList
, but nothing happens. I’ve tried using console.log
after updating it, and the new item does get added to the array, but the FlatList
does not seem to re-render.
2
Answers
Force Re-render: Another way is to use the extraData prop, which forces FlatList to re-render when data changes.
Update the addItem to below given function.