Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the exact usage of componentWillUpdate in ReactJS?

Tags:

reactjs

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?

like image 778
Suresh Ponnukalai Avatar asked Oct 12 '15 07:10

Suresh Ponnukalai


1 Answers

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.

like image 127
Bhargav Ponnapalli Avatar answered Sep 20 '22 13:09

Bhargav Ponnapalli