I'm working with API data that comes from a table which has many relations with other tables. It uses reference tables and join tables. I have to use this data shared across multiple (if not all) components. Is it bad to make all the api calls right in the App.js/root component? why or why not?
EDIT: I am currently using redux, and thinking of storing all the reference table values in global state, so I can do a lookup wherever needed.
example response from API
{
"name": "Adam"
"schoolId": 2,
"countryId": 6,
}
School example reference table
{
"id": 2,
"name": "High School",
}
Country example reference table
{
"id": 6,
"name": "Bulgaria"
}
App.js
function App({ getCountries, getSchools }) {
// Get all reference table data
useEffect(() => {
getCountries();
getSchools();
// get...(); All other reference tables
}, [
getCountries,
getSchools,
]);
return (
<Provider store={store}>
<div className="App">
<Router>
<Fragment>
<div className="d-flex align-items-stretch wrapper">
<div id="sidebar">
<div className="sidemenu position-fixed">
<Sidebar />
</div>
</div>
<div className="content">
<Navbar />
<main className="container-fluid">
<Switch>
<Route component={Routes} />
</Switch>
</main>
</div>
</div>
</Fragment>
</Router>
</div>
</Provider>
);
}
export default connect(null, { getCountries, getSchools })(App);
Calling all APIs in the root component of your app poses the risk of your entire app re-rendering whenever a tiny bit of data changes. It is better practice to have child components down the render tree call APIs to fetch the tiny bits of data they need whenever possible, I would say using the useEffect hook or the corresponding APIs if you are using class based components. That way, a change in one piece of data causes a particular component to rerender but leaves the other components intact in the DOM.
To further improve performance, you bring in a state management library like Redux into play and make use of caching.
It is not good practice to call APIs to fetch data that isn't necessary yet. That is incurring unnecessary costs and unnecessarily burdening processing resources.