Search code examples
ruby-on-railsreactjsecmascript-5react-rails

How to implement a PureComponent in ES5


A bit of context: Rails Application running react-rails on sprockets (No es6) React version 15.4.1.

This means our components are defined like: var ComponentName = React.createClass(...

I'm attempting to use a callback to pass state from a child component to a parent component. The problem begins because the updating of the parent state causes the child component to re-render resulting in a stack level too deep error.

I was told I could get the child component to stop re-rendering using a PureComponent but I have not found an implementation in ES5.

Does anyone have any light on this?


Solution

  • PureComponent is basically just a way to automatically do a shouldComponentUpdate that does a shallow comparison of the props and state. While you can't use PureComponent with React.createClass, you can use shouldComponentUpdate. You could either implement your own comparison function, or use the one in react-addons-shallow-compare.

    var shallowCompare = require('react-addons-shallow-compare');
    
    var Example = React.createClass({
      shouldComponentUpdate: function(nextProps, nextState) {
        return shallowCompare(this, nextProps, nextState);
      },
    
      // rest of the component
    });