javascriptreactjsreactjs-flux

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?

Solution

  • 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.