Logo


Lifecycle of Components


In React, Every Component have the Lifecycle ,which we managed in its three phases
The three phases are: Mounting, Updating, and Unmounting.


Mounting


Mounting means inserting elements into DOM,when we mounts the component,Reacts automatically calls its methods by default

  • 1. constructor()
  • 2. getDerivedStateFromProps()
  • 3. render()
  • 4. componentDidMount()

The render() method is necessary and will always be called, the others are optional and will be called if you define them


Constructor

The constructor() method is called before anything else, when the component is initiated, and it is the natural place to set up the initial state and other initial values. The constructor() method is called with the props, as arguments, and you should always start by calling the super(props) before anything else, this will initiate the parent's constructor method and allows the component to inherit methods from its parent (React.Component).


1import React from 'react';
2import ReactDOM from 'react-dom';
3
4class Header extends React.Component {
5  constructor(props) {
6    super(props);
7    this.state = {favoritecolor: "red"};
8  }
9  render() {
10    return (
11      <h1>My Color is {this.state.favoritecolor}</h1>
12    );
13  }

About

Moiz is a software engineer from Arid University with a passion for writing tech tutorials and doing coding. I am continously produce JavaScript and other web development technology tutorials in concepts through easy-to-understand explanations written in plain English.I have expertise in next js ,react js ,javascript,html,bootstrap and node js.

Follow him on Twitter

Hassan is a software engineer from kohat university of science and technology with a passion for writing tech tutorials and doing javascript practices on daily basis.I have expertise in next js ,react js ,javascript,html,bootstrap and node js. Problem Solving and making concpets is my strong point.

Follow him on Twitter

Tags

Click to see all tutorials tagged with:

© Copyright 2023 Pak Annonymous | Back To Homepage | Privacy Policy
Share