React componentDidMount() Method
The format of the componentDidMount() method is as follows:
componentDidMount()
The componentDidMount() method is called immediately after the component is mounted (inserted into the DOM tree).
Initialization that depends on DOM nodes should be placed in the componentDidMount() method.
The following example will first outputexample, then usecomponentDidMount()method to set the output after the component is mountedgoogle:
Example
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {favoritesite: "example"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritesite: "google"})
}, 1000)
}
render() {
return (
<h1> My favorite website is{this.state.favoritesite}</h1>
);
}
}
Try it »
React Component Lifecycle