React Lifecycle
vIn
React every components has various lifecycle methods
vAll
the lifecycle methods are comes under the 4 phases
1.Initial
Phase
2.Mounting
Phase
3.Updating
Phase
4.Unmounting
Phase
Initial
Phase
*
In this phase the
developer has to define the props and initial state of the component this is
generally done in the constructor of the component.
© getDefaultProps():
It is used to specify
the default value of this.props.It is invoked before the creation of the
component.
© getInitialState():
It is used to specify
the default value of this.state.It is invoked before the creation of the
component.
Mounting
Phase
After the
initialization of the component is completed ,the component is mounted on the
DOM and rendered for the first time in the webpage.
*
componentWillMount() function:
This function is invoked before the component is
mounted on the DOM.
Ø This
function gets invoked once before the render() function is executed for the
first time.
Ø In
the case, when you call setState() inside this method, the component will not
re-render.
Changes in index.js
componentWillMount()
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root')
);
class Lifecycle extends React.Component{
constructor(){
super();
this.state={initialvalue:"Welcome",name:" Students"}
}
componentWillMount(){
alert("Learn ReactJs");
}
render(){
return<h1>{this.state.initialvalue}{this.state.name}</h1>
}
}
var mystyle={color:'green',textAlign:'center'}
const element =<div style={mystyle}><Lifecycle /></div>;
root.render(element);
Output
*
componentDidMount()
function:
This function is invoked after the component is
mounted on the DOM.
Ø This
function gets invoked once after the render() function is executed for the
first time.
Ø Now,
you can do any DOM querying operation.
ComponentDidMount()
Changes in index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(
document.getElementById('root')
);
class Lifecycle extends React.Component{
constructor(){
super();
this.state={initialvalue:"Welcome",name:" Students"}
}
componentWillMount(){
alert("Learn ReactJs");
}
render(){
return<h1>{this.state.initialvalue}{this.state.name}</h1>
}
componentDidMount(){
setTimeout(()=>{
this.setState({initialvalue:"Thank You"})},5000)
}
}
var mystyle={color:'green',textAlign:'center'}
const element =<div style={mystyle}><Lifecycle /></div>;
root.render(element);
Output
After 5 seconds initial value will be changed from ‘welcome’ -> ‘Thank you’
No comments:
Post a Comment