0

I have made a React component called Graph:

<Graph
    chartOptions={{forceY: [0, 100]}}
    graphData={graphData}
/>

I want to implement shouldComponentUpdate to draw the graph only when needed. I looked into using the PureRenderMixin which compares the props. However, my chartOptions is a new object with the same contents every time this code is run. I want the chartOptions to be the same object every time, so I can properly compare the props. How can I do this?

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
  • Refer to understand shouldComponentUpdate: http://stackoverflow.com/questions/28353702/reactjs-check-props-and-state-on-shouldcomponentupdate – Venkat.R Jan 07 '16 at 09:29
  • You can move it to an instance property or variable outside the component. – Brigand Jan 07 '16 at 09:52

1 Answers1

0

Assuming the order of values in forceY is important, the following code should work...

In Graph component -

    shouldComponentUpdate: function(newProps, newState){
       if(!_.isEqual(this.props.chartOptions.forceY, newProps.chartOptions.forceY)){
        return false;
       }

       return (newProps != this.props && newState != this.state);
    }

The _ is a lodash import. You can use this library to compare the new array with the existing one. Or you can implement your own equality comparer based on this post.

Community
  • 1
  • 1
hazardous
  • 10,627
  • 2
  • 40
  • 52