InterviewSolution
| 1. |
Why API calls are to be made from componentDidMount and not in constructor/componentWillMount |
|
Answer» This is recommended to avoid side effects. Render method will get CALLED immediately after the componentWillMount and no way we can make the render method wait until the API has returned. Constructor is a place where we define the variables and not make any API calls. API calls can have side effects and should not be used inside constructor React expects state to be AVAILABLE as render function will be called next after componentWillMount and code can break if any MENTIONED state variable is missing which may occur in case of ajax API calls One more reason is If we are doing server-side rendering of React components componentWillMount will get called on the server-side and again on the CLIENT, resulting in calling fetch two times. Hence, this is not definitely the place where we should integrate our APIs. NOTE: A side effect is any application state change that is observable outside the called function other than its return value. Eg: modifying a GLOBAL variable |
|