What Is Life Cycle Method In Rectjs ? With It's Example

React.js

Nicesnippets

263

21-01-2020


In this tutorial i would like to explain about component life cycle method. component have different types of method. life cycle means component create to component end stories.

Component have three types of life cycle phase

1. Mounting

2. Updating

3. Unmounting

Component have many types of method like

constructor()

The constructor for a React component is called before it is mounted. When implementing the constructor for a React.Component subclass, you should call super(props) before any other statement. Otherwise, this.props will be undefined in the constructor, which can lead to bugs.

render()

the render() method is required in class component. it's return HTML Code.

componentDidMount()

This method call when component invoked. componentDidMount() is invoked immediately after a component is mounted. this is a good place to instantiate the network request.

componentDidUpdate()

The componentDidUpdate() method call after updating. This is also a good place to do network requests as long as you compare the current props to previous props.

componentWillUnmount()

componentWillUnmount() method unmount before component is destroyed. Perform any necessary cleanup in this method.

You have to understand rectjs life cycle in detail then click here http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram

Life Cycle Example

/src/App.js file

import React from 'react'

class App extends React.Component{

constructor(){

console.warn('constructor call')

super();

this.state = {

title:'App Component'

}

}

componentDidMount(){

console.warn('componentDidMount call')

}

componentWillUnmount(){

console.warn('componentWillUnmount call')

}

componentDidUpdate(){

console.warn('componentDidUpdate call')

}

render(){

console.warn('render call')

return(

<div>

<h1>App Component</h1>

</div>

)

}

}

export default App;

I hope it can help you...


Recommended Posts