'Can someone explain to me what the correct way to pass the data is?

Consider this scenario: there is only 1 screen in the app - App.js.

There are 5 components on that screen: compA, compB, ...

So there is only 1 api to get the all the data using for this app:

axios.get('database/getAll')

Let's say there are 100 objects returned from the api. Take not that I only want to pass only a subset of data to each component.

Scenario 1

I call the API in the screen App.js. Then I also pass all the data to every component. Meaning I pass all 100 object to each component, and filter the data in the component

Scenario 2

I call the API in App.js. I filter the data in the useEffect hook of App.js. Then I pass the filtered data to their respective component.

useEffect(() => {
    axios.get('alldata').then((res) => {
        let allData = res.data;
         
        let compAData = allData.filter((data) => data.category === 'compA')
        setStateCompAData(compAData);
        let compBData = allData.filter((data) => data.category === 'compB')
        setStateCompBData(compBData);
        let compCData = allData.filter((data) => data.category === 'compC')
        setStateCompCData(compCData);
    })
},[])

return (<div>
    <CompA data={stateCompAData}/>
    <CompB data={stateCompBData}/>
    <CompC data={stateCompCData}/>
</div>)

Scenario 3

I don't call the API in App.js - I call the API every time in the components useEffect and filter in their respective component.

So what is the correct use case scenario?



Solution 1:[1]

All 3 will achieve the same results, but scenario 2 is likely best practice. However, I would not recommend maintaining 3 different state values, but instead having a single object state containing the different data structured as such

{
   dataA: ...,
   dataB: ...,
   dataC: ...
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mynameisgeoff123