Giant Elk
Giant Elk

Reputation: 5685

Stop ReactJS from rendering every time this.setState() is called?

How can I stop <AnotherComponent/> from rendering every time this.setState() get's called? Simple example below, although my app is much more complex. I have a bunch of subcomponents for a simple game, i.e. separate components to A) update the score, B) show a push button and C) show random images.

Everytime setState() is called it renders all the sub components, I want to STOP it from rendering at least one specific component. I'm trying to wrap my head around using shouldComponentUpdate, not sure if I should use this in the parent component or child:

var App = React.createClass({
   getInitialState: function() {
      return {
         isA: false
      };
   },

    handleClick: function() {
        this.refs.SomeComponent.myAction();
        if ( localStorage.showMsg ) {
            this.setState( {isA: true} );   
        } else {
            this.setState( {isA: false} );
        }

    },

   render: function() {
      return (
        <div>
           <SomeComponent handleClick={this.handleClick} ref="SomeComponent" />
           <AnotherComponent />
         </div>
      );
   } 
}); 

Upvotes: 1

Views: 4827

Answers (2)

edoloughlin
edoloughlin

Reputation: 5891

Why do you want to stop the render? If a component's props and state haven't changed then, although it will render, the DOM will not be updated. If you have some really expensive comuptation in your render then you should by all means use componentShouldUpdate, bearing in mind the caveat from the docs:

By default, shouldComponentUpdate always returns true to prevent subtle bugs when state is mutated in place, but if you are careful to always treat state as immutable and to read only from props and state in render() then you can override shouldComponentUpdate with an implementation that compares the old props and state to their replacements.

If you're worried about top-heavy state, you should look at the Flux pattern and also Fluxxor for a nice implementation.

Upvotes: 1

Brigand
Brigand

Reputation: 86270

shouldComponentUpdate should only be used as an optimization. Because render should be a function of props and state, if react wanted to rerender everything at random intervals, your application should still behave correctly.

Upvotes: 5

Related Questions