reactjsreact-nativereact-hooksreact-asyncreact-flatlist

Updating FlatList data with useState infinitely recurs in React Native


I'm trying to set the data for a flatlist with useState, but updating the state causes the component to re-render, so it calls the getInventory function again and infinitely recurs, crashing the app. I'm using a function component, not class. If I put the getInventory bit in a useEffect, it doesn't crash, but the useEffect function in the InventoryItem components is constantly called. I can't see what I'm doing wrong

    const [data, setData] = useState([]);

    getInventory().then((list) => {
        setData(list)
    })    

    const renderItem = ({item}) => {
        return <InventoryItem item={item}/>
    };

    return (
        <SafeAreaView>
            <FlatList       
                data={data}
                renderItem={renderItem}
                keyExtractor={item => item.id}
            />  
        </SafeAreaView>
    );

Solution

  • Use useEffect with an empty dependencies array, so it would run only once:

    useEffect(() => {
      getInventory().then((list) => {
          setData(list)
      })
    }, [])    
    

    And you can also remove the redundant arrow function, since setData is a function that expects a single argument:

    useEffect(() => {
      getInventory().then(setData)
    }, [])