Each component has several “lifecycle methods” that you can override to run code at particular times for particular result in the process.
A Component in ReactJS has a lifecycle which you can monitor and manipulate during phases.
These are the main phases of Components:
Lifecycle of ReactJS Component
React has four in-built methods that gets called in a order while mounting a component.
Constructor() – is called before anything else initialized in a component. It is called along with props, as arguments. You should always call super(props) as it initialize parent’s constructor methods and props and allow the component to inherit methods from its parent (React.Component).
class Tutorial extends React.Component { constructor(props) { super(props); this.state = {tutorial: "ReactJS"}; } render() { return ( <h1>I am learning {this.state.tutorial}</h1> ); } } ReactDOM.render(<Tutorial />, document.getElementById('root'));
getDerivedStateFromProps – This method is called just before rendering any element(s) in the React DOM. It accept state as an argument, and returns an object with changes to the state.
Tutorial.js
import React, { Component } from "react"; class Tutorial extends React.Component { constructor(props) { super(props); this.state = {tutorial_name: "PHP & MySQL"}; } static getDerivedStateFromProps(props, state) { return {tutorial_name: props.new_tutorial}; } render() { return ( <h1>My Favorite Color is {this.state.tutorial_name}</h1> ); } } export default Tutorial;
index.js
import React from "react"; import ReactDOM from "react-dom"; import Tutorial from './Tutorial'; //Rendering component... ReactDOM.render(<Tutorial new_tutorial="ReactJS Online Share Query."/>, document.getElementById('root'));
render
The render() method is the only mandatory method in ReactJS. It actually results the HTML to the DOM.
import React from "react"; import ReactDOM from "react-dom"; class Tutorial extends React.Component { render() { return ( <h1>I am learning ReactJS from Share Query.</h1> ); } } //Rendering component... ReactDOM.render(<Tutorial/>, document.getElementById('root'));
componentDidMount
componentDidMount() is invoked immediately after a component is rendered(inserted into the tree). Initialization that requires DOM nodes should go here.
import React from "react"; import ReactDOM from "react-dom"; class Tutorial extends React.Component { constructor(props) { super(props); this.state = {tutorial: "ReactJS"}; } componentDidMount() { setTimeout(() => { this.setState({tutorial: "PHP & MySQL"}) }, 1000) } render() { return ( <h1>I am learning {this.state.tutorial}</h1> ); } } //Rendering component... ReactDOM.render(<Tutorial/>, document.getElementById('root'));