React Component Lifecycle - Mounting Phase
As we have seen the basics of the React Component Lifecycle, lets get into the action!
Today we will look into the Mounting phase. As discussed earlier, there are 3 major methods:
- Constructor
- render
- componentDidMount
In react, the calling sequence is Constructor 🠊 render 🠊 componentDidMount.
Lets look at an example:
class ReactLifecycle extends React.Component {
constructor() {
super();
console.log("Constructor of ReactLifecycle is called.");
}
componentDidMount() {
console.log("componentDidMount method of ReactLifecycle is called.");
}
render() {
console.log("Render method of ReactLifecycle is called.");
return <h1>Hello World!</h1>;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<ReactLifecycle />, rootElement);
Output:
- Notice the sequence in which the messages were logged in the console:
- constructor()
- render()
- componentDidMount()
- componentDidMount()
- This method is called after component is rendered into the DOM.
- It is a perfect place to make Ajax calls to get data from the server.
- Please note that when a component is rendered, all of its children are also rendered recursively.
Comments
Post a Comment