Why is calling APIs in `componentDidMount()` considered a best practice?

Tell us what’s happening:
Describe your issue in detail here.
Why is calling APIs in componentDidMount() considered a best practice ? Wouldn’t it make sense to call the API before rendering ?

  **Your code so far**

class MyComponent extends React.Component {
constructor(props) {
  this.state = {
    activeUsers: null
componentDidMount() {
  setTimeout(() => {
      activeUsers: 1273
  }, 2500);
render() {
  return (
      {/* Change code below this line */}
      <h1>Active Users: </h1>
      {/* Change code above this line */}
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.93 Safari/537.36

Challenge: Use the Lifecycle Method componentDidMount

Link to the challenge:

You need something as your initial state that is not async or else when the components rendered the async state will be undefined, and this is why we make the calls in componentDidMount, and update the state from there.

React now has a better way to do this that is pretty new however:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.