ScanSkill

componentDidMount()

The componentDidMount() is initiated right after the component is rendered in the DOM. It is called only once so API calls statements are written inside the componentDidMount() and other functions that requires the component to be rendered in the DOM first are called here.

Syntax

componentDidMount(){
    functions here....
}

Example

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "John"};
  }
  componentDidMount() {
    //change state after 1 second
    setTimeout(() => {
      this.setState({name: "Billy"})
    }, 1000)
  }
  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

Here, the state name is changed 1 second after the component renders.