Should I call Axios in each component on a page or multiple times on the parent page for each component?

Viewed 562

I'm looking to understand what is the best practice when it comes to utilizing Axios to fetch data from Node.js. I have multiple graphs, cards and other components on the given page and am trying to understand if I should be calling Axios on the parent page for each component and passing the values as props to the component or rather call Axios and the data in each component itself.

Trying to understand what is seen as best practice.

From my understanding it is better to let each component be self standing (i.e. call its own data from the DB) rather than once on the page.

Much appreciated.

2 Answers

It's better to have a layer between components and axios (a class / function that wraps axios for example).

Then, each components will call that class and the class will call axios. By doing this, you can let each component fetch its own data.

Then you can add a logic so that if 2 components try to fetch the same data, you will cache it and only fetch it once.

By doing this, you keep each component self sufficient, and you reduce the number of calls to the server

If the data is used only in a sub-component, there is no need to query it one level above, do it in the component itself for the sake of encapsulation: it will allow you to not leave behind useless axios code should you remove the sub-component later.

If the data is shared by multiple components, do the query once and pass it to every child that needs it.

N.B. What is a common practice however, is to have a component that is purely "presentational" (with no logic, only receiving props), and a parent component that does the query (and maybe some other logic) and passes the result as props to the presentational one. It allows to re-use the graphical layout of the presentational component with different input data somewhere else.

Related