React: Use the Lifecycle Method componentDidMount

rthefounding

Randy Rivera

Posted on November 9, 2021

React: Use the Lifecycle Method componentDidMount
  • The best practice with React is to place API calls or any calls to your server in the lifecycle method componentDidMount(). This method is called after a component is mounted to the DOM. Any calls to setState()here will trigger a re-rendering of your component. When you call an API in this method, and set your state with the data that the API returns, it will automatically trigger an update once you receive the data.

  • Below is a mock API call in componentDidMount(). It sets state after 2.5 seconds to simulate calling a server to retrieve data. This example requests the current total actives users for a site. In the render method, render the value of activeUsers in the h1 after the text Active Users:.

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

Enter fullscreen mode Exit fullscreen mode
  • Answer:
class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      activeUsers: null
    };
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({
        activeUsers: 2324
      });
    },1500);
  }
  render() {
    return (
      <div>
        <h1>Active Users: {this.state.activeUsers} </h1>
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
rthefounding
Randy Rivera

Posted on November 9, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

React: Add Event Listeners
javascript React: Add Event Listeners

November 12, 2021

React: Components
javascript React: Components

September 25, 2021