Wednesday 8 April 2015

React - Skip Virtual Dom Diff


shouldComponentUpdate return false to skip the re-rendering(Virtual Dom Diff). Below example skip the re-render after state no value greater than 10.

In your app has multiple component then you won't re-render full app for state or props changes. you put some condition wether re-render is necessary. So shouldComponentUpdate function should be light weight function.


var Hello = React.createClass({
    getInitialState:function(){
        return {name:"vimal",no:1}
    },
    shouldComponentUpdate:function(np,ns){
    if(ns.no<11)
    return true;
    else
    return false;
    },
    click:function(){
        this.setState({name:"vimalesan",no:this.state.no+1});
    },
    render: function() {
        return <div onClick={this.click}>Hello {this.props.name} {this.state.name+"-"+this.state.no}</div>;
    }
});

React.render(<Hello name="World" />, document.getElementById('container'));