shouldComponentUpdate() check

shouldComponentUpdate check to avoid expensive re-renders

React Components re-render every time their props or state change.
So imagine having to render the entire page every time there in an action. That takes a big load on the browser.
That’s where ShouldComponentUpdate comes in, whenever React is rendering the view it checks to see
if shouldComponentUpdate is returning false/true. So whenever you have a component that’s static do yourself a favor and return false.
Or if is not static check to see if the props/state has changed.

Bad

  1. const AutocompleteItem = (props) => {
  2. const selectedClass = props.selected === true ? "selected" : "";
  3. var path = parseUri(props.url).path;
  4. path = path.length <= 0 ? props.url : "..." + path;
  5. return (
  6. <li
  7. onMouseLeave={props.onMouseLeave}
  8. className={selectedClass}>
  9. <i className="ion-ios-eye"
  10. data-image={props.image}
  11. data-url={props.url}
  12. data-title={props.title}
  13. onClick={props.handlePlanetViewClick}/>
  14. <span
  15. onMouseEnter={props.onMouseEnter}
  16. >
  17. <div className="dot bg-mint"/>
  18. {path}
  19. </span>
  20. </li>
  21. );
  22. };

Good

  1. export default class AutocompleteItem extends React.Component {
  2. shouldComponentUpdate(nextProps, nextState) {
  3. return nextProps.url !== this.props.url ||
  4. nextProps.selected !== this.props.selected;
  5. }
  6. render() {
  7. const {props} = this;
  8. const selectedClass = props.selected === true ? "selected" : "";
  9. var path = parseUri(props.url).path;
  10. path = path.length <= 0 ? props.url : "..." + path;
  11. return (
  12. <li
  13. onMouseLeave={props.onMouseLeave}
  14. className={selectedClass}>
  15. <i className="ion-ios-eye"
  16. data-image={props.image}
  17. data-url={props.url}
  18. data-title={props.title}
  19. onClick={props.handlePlanetViewClick}/>
  20. <span
  21. onMouseEnter={props.onMouseEnter}>
  22. <div className="dot bg-mint"/>
  23. {path}
  24. </span>
  25. </li>
  26. );
  27. }
  28. }