Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: Compare props and state on shouldComponentUpdate

I want to check all properties and state if they are changed, return true if any changed and make a base component for all my root components.

I'm wondering if it won't be the best practice and make my components slow. Also, what I did always returns true:

shouldComponentUpdate: function(newProps, newState) {
    if (newState == this.state && this.props == newProps) {
        console.log('false');
        return false;
    }
    console.log('true');
    return true;
},
  1. Is there anything wrong with my code?
  2. Should I check for every variable inside props and state?
  3. Won't check for objects inside them make it slow depending on their size?
like image 564
Guilherme David da Costa Avatar asked Dec 19 '22 07:12

Guilherme David da Costa


2 Answers

It is considered best practice to compare props and state in shouldComponentUpdate to determine whether or not you should re-render your component.

As for why it's always evaluating to true, I believe your if statement isn't performing a deep object comparison and is registering your previous and current props and state as different objects.

I don't know why you want to check every field in both objects anyway because React won't even try to re-render the component if the props or state hasn't changed so the very fact the shouldComponentUpdate method was called means something MUST have changed. shouldComponentUpdate is much better implemented to check maybe a few props or state for changes and decide whether to re-render based on that.

like image 62
Ganonside Avatar answered Dec 31 '22 03:12

Ganonside


I think there's a problem in most of the tutorials I've seen (including the official docs) in the way that stores are accessed. Usually what I see is something like this:

// MyStore.js

var _data = {};

var MyStore = merge(EventEmitter.prototype, {

  get: function() {
    return _data;
  },

  ...

});

When I used this pattern, I found that the newProps and newState in functions like shouldComponentUpdate always evaluate as equal to this.props and this.state. I think the reason is that the store is returning a direct reference to its mutable _data object.

In my case the problem was solved by returning a copy of _data rather than the object itself, like so:

  get: function() {
    return JSON.parse(JSON.stringify(_data));
  },

So I'd say check your stores and make sure you're not returning any direct references to their private data object.

like image 23
Adam Stone Avatar answered Dec 31 '22 01:12

Adam Stone