1

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,

1
  • 1st one is better, you only need to call API once and using context you can pass all state to the child components Commented Nov 5, 2020 at 4:29

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

How does context get "too cluttered"? Especially compared to redux...?
What I've noticed is that I will tend to use context with useReducer, and by the time I've got 2 or 3 things that rely on this architecture, I'm already creating a reducer file, between my 'globalState.js' file from context and 'reducers.js' file for my useReducers I might as well just use redux and separate the code accordingly, because with redux things are a lot more organized and concise than with the other way just mentioned. both my gloablstate and reducer files tend to get large fast and multiple things are taking place on them

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.