Each component in react live a life - from birth to death.
Main three stages of the lifecycle of a component are:
-
Mounting
: Birth of the component -
Updating
: Growth of the component -
Unmounting
: Death of the component
we have many method in these lifecycle, but i'm talk about four mostly used methods. These methods can only used in class components.
render()
render() {
console.log('rendering')
return (
<div>
<div>Parent Component</div>
</div>);
}
Other ways can be used, but this one must be declared. Our component is created at this stage and is added to the DOM. Rendering of the component to the DOM
componentDidMount()
The componentDidMount() is called after the component is rendered.
class... {
constructor(props) {
super();
this.state = {
color : ''
}
}
componentDidMount() {
this.setState({
color: 'red'
})
}
render() {
<h1>I, a header element, is born! My color is {this.state.color}</h1>
}
}
componentdidupdate()
Once the update is complete, this method is called. It accepts as input the previous props, previous state. This is an ideal location for causing side effects and making network requests for the updated props.
componentDidUpdate(prevProps) {
if(this.props.color !== prevProps.color) {
console.log('component updating')
}
}
shouldComponentUpdate()
When state or props change, you'll want a component to re-render. You do, however, have control over this behaviour.
You can control whether the component is rerendered by returning a boolean (true or false) within this lifecycle method.
shouldComponentUpdate(){
console.log('shouldComponentUpdate')
return true
}
Top comments (0)