Let’s say I have a function that retrieves data from API and the API returns array of objects. Each object has a lot of fields(20 or so). Now I want to use ONLY ‘id’ and ‘name’ of each object.
Is it better to use that map function to reduce the objects to 2 fields each or would it be better to just pass the object as is and let the Dropdown component destructure the fields itself?
const SomeComponent () =>{
const [companies, setCompanies] = useState([]);
const fetch =async () => {
await api.get("/companies").then((response) => {
const rows = response.data.rows;
const updateCompanies = rows.map((item) => ({
//extract only name and id of statusLabels
id: item.id,
name: item.name,
}));
setCompanies(updateCompanies); //set companies
})
};
useEffect(()=>{
if(companies.length === 0){
(async () => await fetch())();
}
},[])
return (
<>
<Dropdown
data={companies}
placeholderStyle={styles.placeholder}
labelField="name"
valueField="id"
placeholder={"Companies"}
onChange={(item) => {
setCompanyFilter(item.id);
}}
style={styles.inputContainer}
/>
</>
)
}
tried passing both ways but i don’t know how to benchmark
2
Answers
In javascript objects are passed by reference, so preformance wise it makes no diference. If you use map() you will create a new array, and new memory space will be allocated (although preformace wise it will have virtualy no impact).
You can read more about the subject here.
Personally, since you have an array with many objects, and even if map creates a new array in memory, if the component does not need the rest of the data I would have done the same for the time being and would have refactored latter along the line when the use of the component will be fixed.
In conclusion, your component may grow further along the development line, and other values of the api response may become necessary before all (or most of) implementations of your component are known. So in the end, it may indeed be better to use the original object.
Passing the whole array of object is probably the best solution as it doesn’t take any more memory nor more time whereas maping does take some time to execute.