简体   繁体   中英

Where should we make an API request in React?

I have always made API's request in ComponentDidMount lifecycle and called setState in the callback. But while digging deep I happened to find out We should not call setState in this lifecycle as it triggers render method again and React also doesn't recommend that.

Then in that case where exactly we should make that request and call setState to use result after that?

You should absolutely make an API call in componentDidMount . What is not recommended is to re-render a big component, instead what you should do is break your UI into small logical components and only re-render only what is needed , not a whole. For example, you have a big component named HomeComponent which has 3 small components called NavComponent , BodyComponent and FooterComponent . You should NOT be calling the API from the componentDidMount of the HomeComponent since calling setState from HomeComponent will re-render all the small components inside HomeComponent , which is not necessary since you know that the navbar or footer is not needed to be re-rendered. Rather from the BodyComponent , because only the body part needs to be re-rendered since its state has changed. So you should be calling the API from the componentDidMount of the BodyComponent , that way you re-render only whats needed.

@Shababb Karim is right but if i were to implement API calls in my project i would add a state management library. Redux is a great way to implement a global state to the app where you can set data from said API. All components that need that data can be attached to the Redux state to get it.

Redux can be a bit of overhead in smaller projects though. In this case there are other options like Flux (although i like Redux more).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM