Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 5344

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 61k
Author
Asked: November 27, 20242024-11-27T08:22:07+00:00 2024-11-27T08:22:07+00:00

React LifeCycle Method | Day 16

  • 61k

What

Every Component in React has a lifeCycle which we can moniter or update During it’s 3 main Phases.

So Every Component has 3 main Phase during it’s Life

1.) Mounting → This Means Adding the Component into the DOM.

2.) Updating → Updating the State or any other data of the Component.

3.) UnMounting → Removing the Component From the DOM.

React Lifecycle Method

How

Mounting

When a Component is rendered in the DOM for the 1st Time then it is called as Mounting.

React has 3 methods that got called During Mounting.

1.) Constructor()

2.) render()

3.) ComponentDidMount()

Before you Move further you should know about this the methods which are prefixed by will are called right before Something happen and the methods which are prefixed by Did are called right after Something happen.

Constructor

The Constructor will called 1st and used for initialize the state and Bind the event handlers.

After that render will be called

Render

After the Component is rendered React will call the ComponentDidMount().

React Lifecycle Method

  • As the Component is Already Rendered if we will try to change state in the componenetDidMount() It will cause a Re-rendering.

Let’s have a Look to this Example

import React,{Component} from "react"  class ReactLifestyle extends Component{   constructor(props){     super(props);     this.state = {count:1}     console.log('In Constructor Method')   }   componentDidMount(){     console.log('IN Component Did Mount')     this.setState({count:2})   }   render(){     console.log('In Render method')     return(       <div>       hi       </div>     )     } }  export default ReactLifestyle; 
Enter fullscreen mode Exit fullscreen mode

The Output of the Code will be 👇

Code Output

As u can see 1st Constructor Method is called then Render Method and then Component Did Mount

Also If we try to set state in the ComponentDidMount then it will cause re-rendering as u can in the output.

componentDidMount

Loading Data Via Ajax

import React, { Component } from 'react'; import axios from 'axios'; import "./Zenquote.css"  class Zenquote extends Component {     constructor(props) {         super(props);         this.state = {quote:"",isloading:true};       }     componentDidMount() {         //WE are adding the setTimeout so can we can get in a Condition when after rendering the Data Fetching takes time.         setTimeout(() =>{         axios.get("https://api.github.com/zen")         .then((res)=>{             console.log(res.data);             this.setState({quote:res.data,isloading:false});         })         .catch((err)=>{             console.log(err);         })     },1000)      }   render() {     return( <div>         {this.state.isloading?          (<p className="circle">         Loading .........         </p>)         : (<div>             <h3>Always Remember ....</h3>             <p>{this.state.quote}</p>         </div>)}      </div>);   } }  export default Zenquote 
Enter fullscreen mode Exit fullscreen mode

  • So in the code every-time we refresh the page we got new quote , I use the axios to fetch the data and also , I have to use the setTimeout to depict that sometime the data fetching take time so at that time we can add a animated Loader.

Loading data using the Async Function →

Async/await make promises easier to write.

Async makes a function return a Promise.

Await makes a function wait for a Promise.

componentDidmount(){     async GetData(){         let res = await fetch('http://github.com.api/users');         console.log(res);     } } 
Enter fullscreen mode Exit fullscreen mode

  • When we Write it will wait for the data to come then move on to another line.

Example →

import React, { Component } from 'react'; import axios from 'axios';  class GithubUsersInfo extends Component {     constructor(props) {         super(props);         this.state = {imgUrl:"",name:"",followers:""};     }     async componentDidMount() {         let user = `https://api.github.com/users/${this.props.user}`         const res = await axios.get(user)         console.log(res);         this.setState({imgUrl :res.data.avatar_url,name:res.data.name,followers:res.data.followers})     }   render() {     return <div>         <h2>Github User Name : {this.state.name}</h2>         <img src={this.state.imgUrl} alt="image"/>         <p>Followers : {this.state.followers}</p>     </div>;   } }  export default GithubUsersInfo 
Enter fullscreen mode Exit fullscreen mode

  • This takes user name as a props.
  • This will gives us the Github User Data.

ComponentDidUpdate →

Code Output

Updating can be done by changing the the State , Props (Changed Form the Parent Side) , or any other External Data.

Like forceUpdate is used to update the things which are not in the state and often they are external Data so to change that we can use the forcedata().

React Lifecycle method

When we update Something Re-rendering Happen after then ComponentDidUpdate() called.

So we can use the ComponentDidUpdate() to save all your data into the database which has been changed .

componentDidUpdate

Example →

import React, { Component } from 'react'; import axios from 'axios'; import "./Zenquote.css"  class Zenquote extends Component {     constructor(props) {         console.log("In Constructor")          super(props);         this.state = {quote:"",isloading:true};       }     componentDidMount() {         console.log("In Component Did Mount")         setTimeout(() =>{         axios.get("https://api.github.com/zen")         .then((res)=>{             this.setState({quote:res.data,isloading:false});         })         .catch((err)=>{             console.log(err);         })     },1000)      }     componentDidUpdate(){         console.log("In Component Did Update")     }   render() {       console.log("Rendering .....")     return( <div>         {this.state.isloading?          (<p className="circle">         Loading .........         </p>)         : (<div>             <h3>Always Remember ....</h3>             <p>{this.state.quote}</p>         </div>)}      </div>);   } }  export default Zenquote 
Enter fullscreen mode Exit fullscreen mode

The Output of the Below Code is :

Code Output

1st the Constructor is called , then rendering happened and then ComponentDidMount got called and in the ComponentDidMount we change the State so this causes the Re-rendering and when we change the state after Re-rendering the ComponentDidUpdate Got called.

Whenever u update something the ComponentDidUpdate got called after Re-rendering. So we can use the Component Did Mount to save the data to the Database.

Also In the Component Did Update we can access the Previous State and the Previous Props so U can use this to compare the State or props with the previous ones.

To use the Previous state and prop u should write like this.

componentDidUpdate(prevProps,prevState){     // Inside this u can use the previous props & the state      console.log(prevProps);     console.log(this.props); } 
Enter fullscreen mode Exit fullscreen mode

  • Remember the 1st argument will be the previous props and the 2nd argument will be previous state.

ComponentWillUnmount()

This will be called when we are removing something from the DOM

ComponentWillUnmount

componenetWillUnmount(){     console.log('In Component Will Unmount')     //It will be called before the removal of the Component. } 
Enter fullscreen mode Exit fullscreen mode

Happy Coding 🙂

beginnersjavascriptprogrammingwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 2k
  • Popular
  • Answers
  • Author

    ES6 - A beginners guide - Template Literals

    • 0 Answers
  • Author

    Understanding Higher Order Functions in JavaScript.

    • 0 Answers
  • Author

    Build a custom video chat app with Daily and Vue.js

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.