react shouldComponentUpdate code example

Example 1: react forwardref

const FancyButton = React.forwardRef((props, ref) => (
  <button ref={ref} className="FancyButton">
    {props.children}
  </button>
));

// You can now get a ref directly to the DOM button:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;

Example 2: componentDidUpdate

componentDidUpdate(prevProps, prevState) {
  if (prevState.pokemons !== this.state.pokemons) {
    console.log('pokemons state has changed.')
  }
}

Example 3: shouldcomponentupdate

shouldComponentUpdate(nextProps, nextState) {
  return true;
}

Example 4: component did mmount

componentDidUpdate(prevProps, prevState, snapshot)

Example 5: shouldcomponentupdate default return

By default, shouldComponentUpdate returns true, but you can override it to return false for cases that you do not want a re-render.

Example 6: react lifecycle

constructor(props) {
  super(props);
  // Don't call this.setState() here!
  this.state = { counter: 0 };
  this.handleClick = this.handleClick.bind(this);
}