I am new to this ReactJS and started learning Component Lifecycle. Now i have doubt about the componentWillUpdate
and componetDidUpdate
. I know that once you send return true
from shouldComponentUpdate
function, it will call componentWillUpdate
. Once the component have updated then componetDidUpdate
will call.
My question is are we really doing anything in the componetWillUpdate
function? I hope we can't use setState
also in that function. What is the exact use of componentWillUpdate function? When it will be useful?
The componentWillUpdate gives you control to manipulate the component just before it receives new props or state. I generally use it to do animations. Let us say, I want to smoothly fade an element out of the view, before removing the dom. This helps.
componentWillUpdate : function(newProps,newState){
if(!newState.show){
$(ReactDOM.findDOMNode(this.refs.elem)).css({'opacity':'1'});
}
else{
$(ReactDOM.findDOMNode(this.refs.elem)).css({'opacity':'0'});;
}
},
componentDidUpdate : function(oldProps,oldState){
if(this.state.show){
$(ReactDOM.findDOMNode(this.refs.elem)).css({'opacity':'1'});
}
else{
$(ReactDOM.findDOMNode(this.refs.elem)).css({'opacity':'0'});;
}
}
https://jsfiddle.net/zupoj3x6/
One of the many many use cases especially when it comes to animations. The idea is to prepare for the state change. Preparation can be in many ways,
you might want to set a variable which might be needed for the render for this particular state
you might want to animate your divs or
dispatch events to clear/set your stores.
Endless use cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With