2

I have a component that is receiving same props always.When I compare them in shouldComponentUpdate() lifecycle,it returns false

shouldComponentUpdate(nextProps,nextState){
  if(this.props === nextProps){return false;} //returns false
  else return true;
}

However If I compare current vs previous state having same value,they work fine and return true

shouldComponentUpdate(nextProps,nextState){
      if(this.state === nextState){return false;}
      else return true; //return true
}

Both state and props are objects(reference type) but why they are behaving differently?

Shaheryar ahmed
  • 101
  • 1
  • 6
  • 2
    You are not comparing *by value*, you are comparing *by reference* – Davin Tryon Jan 29 '19 at 09:25
  • then why its giving true when I compare state which is also reference type? – Shaheryar ahmed Jan 29 '19 at 09:30
  • 2
    I think you should only use `shouldComponentUpdate()` for a deep `prop or State` object and match something like `this.props. === nextProps.` without just reference comparison `(this.props=== nextProps)` (from @DavinTryon 's comment ) – Anandhu Jan 29 '19 at 09:30
  • @Shaheryarahmed props are by default immutable in react. But state is recommended to be immutable https://stackoverflow.com/a/47471276/6727189 – Anandhu Jan 29 '19 at 09:33
  • 1
    @Shaheryarahmed if no state transition has occurred, React *might* use the same state object, so the references are the same. But in order to *always* detect changes, you must use deep compare. – Davin Tryon Jan 29 '19 at 09:37
  • @David Tryon do you want to say,this.props and nextProps are entirely different objects(different reference),whereas this.state and nextState are same objects (same reference)?? – Shaheryar ahmed Jan 29 '19 at 10:49

0 Answers0