About calling API in reactjs

I have a question about calling API in react.

Example in the website. We have a lot of page. Each page has a lot of components. And each component has its own data need to get in server.

I see we have two way to call API is:

First. We call all API of each page in a root of each page then set the data to state. After that, we pass data to children Component.

Second. In each component, we call its API to get its data then set the data to component 's state.

So which is better. I need an explain about that.

Thanks you,

Upvotes: 1

Views: 79

Answers (2)

4cody
4cody

Reputation: 354

As noted in the previous answers/comments you could do either one of these. If you plan to use redux it might be easier to chain the api calls in a single action w/ thunk that gets ran on main component load.

Context or Redux would do you well so you don't have to pass tons of data through prop levels.(prop drilling)

I would suggest Redux, IMO context gets too cluttered and by the time you've properly atomized your code to clean up everything you may as well have just went through the overhead of adding redux.

What you should ask yourself is-

Does it make sense to have all this data load at the same time? Is it appropriate for some api calls to be made from the components that will use them?

You have creative license to do what works best for you.

Upvotes: 1

Pavan Kalyan
Pavan Kalyan

Reputation: 407

There are many ways to pass Data through out the components.

If the application is small and there are small number of child components you can go by making calls in Root folder.

There would be some components that always doesn't render and only rendered based on specific conditions at this point you can go by making calls from that component.

Using redux and redux thunk is always an option if the data is needed in many components and data can be accessed at any point of time.

Upvotes: 1

Related Questions