Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active February 27, 2020 11:00
Show Gist options
  • Save ross-u/4edd1ccc2edf70919df3400fac831dc6 to your computer and use it in GitHub Desktop.
Save ross-u/4edd1ccc2edf70919df3400fac831dc6 to your computer and use it in GitHub Desktop.
React Lifecycle methods - I Mounting - componentDidMount()

React | Lifecycle methods


I - Mounting or First Render

These methods are called in the following order when an instance of a component is created and inserted into the DOM:

  1. constructor()
  2. render()
  3. componentDidMount()

componentDidMount()

  • componentDidMount() is called immediately after component render() , after the component is mounted (inserted into the DOM).
  • Since the render() method is already executed, DOM will be already present. Which means that we can reference DOM and our component inside componentDidMount().
  • We should be aware that calling setState() here will lead to the re-rendering of the component (can affect performance).
// ...
class Clock extends React.Component {
constructor(props) {
// ...
console.log('IN CONSTRUCTOR');
};
// custom methods and lifecycle methods go after the `constructor`
componentDidMount() { // <--- RUNS RIGHT AFTER THE INITIAL `render()`
/* our code to run after `render()` is finished
and component is mounted onto the DOM */
console.log('IN "COMPONENT DID MOUNT"');
}
render() {
console.log('IN RENDER');
return (
<div>
<h1>Clock</h1>
<h2>Year</h2>
<p>{this.state.year}</p>
</div>
);
} // ⮕ After`render` is done the React component “mounts” onto the DOM.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment