react update state in shouldcomponentupdate code example

Example 1: componentDidUpdate

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

Example 2: lifecycles if reactjs

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  componentDidMount() {  }
  componentWillUnmount() {  }
  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Example 3: shouldcomponentupdate

shouldComponentUpdate(nextProps, nextState) {
  return true;
}

Example 4: 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.

Tags:

Misc Example