Immutable data

"Mike, I have a question though. All said and done, why does PureRenderMixin perform shallow comparison in the first place? Should it not perform a deep comparison so that we will always have better performance?" Shawn was not very happy with PureRenderMixin.

"Well, there is a reason for this. Shallow comparison is very cheap. It does not take much time. Deep comparison is always expensive. Therefore, PureRenderMixin does shallow comparison, which is good enough for most of the simple use cases," said Mike.

"However, React does provide us an option of defining our own version of shouldComponentUpdate as we saw earlier. We can completely short-circuit the re-rendering process by just returning false from shouldComponentUpdate or we can compare only those props that are required by our component."

"True, just like we had written shouldComponentUpdate for the BookRow component right?" asked Shawn.

// src/BookRow.js

export default React.createClass({
  shouldComponentUpdate(nextProps, nextState) {
    return nextProps.title !== this.props.title ||
           nextProps.author_name !== this.props.author_name ||
           nextProps.edition_count !== this.props.edition_count;
  },

  render() {
    return(
      <tr style={this.props.style}>
        ..
      </tr>
    );
  }
});

"Exactly, Shawn. If needed, you can also perform a deep comparison as per the requirements of your component when needed."

// custom deep comparison as per requirement
shouldComponentUpdate(nextProps, nextState) {
    return nextProps.book.review === props.book.review;
}

"Shawn, another option we have is using immutable data. Comparing immutable data with each other is very easy as it will always create new data or objects instead of mutating the existing ones."

// pseudo code 
book_ids = [1, 2, 3]
new_book_ids = book_ids.push(4)
book_ids === new_book_ids # false

"Therefore, we just have to compare the reference of the new object with the old object, they are always same when the values are equal and they are always different when values are unequal. Therefore, if we use immutable data for our props and state, then PureRenderMixin will work as expected." said Mike.

Note

Check http://facebook.github.io/immutable-js/ as an option for using immutable data for state and props.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.186.115