DEV Community

Randy Rivera
Randy Rivera

Posted on

React: Optimizing Re-Renders with shouldComponentUpdate

  • FreeCodeCamp states that if any component receives new state or new props, it re-renders itself and all its children. This is usually okay. But React provides a lifecycle method you can call when child components receive new state or props, and declare specifically if the components should update or not. The method is shouldComponentUpdate(), and it takes nextProps and nextState as parameters.

  • You can use shouldComponentUpdate() to prevent this by comparing the props. The method must return a boolean value that tells React whether or not to update the component.

  • Code:

class OnlyEvens extends React.Component {
  constructor(props) {
    super(props);
  }
  shouldComponentUpdate(nextProps, nextState) {
    console.log('Should I update?');
    // Change code below this line
    return true;
    // Change code above this line
  }
  componentDidUpdate() {
    console.log('Component re-rendered.');
  }
  render() {
    return <h1>{this.props.value}</h1>;
  }
}

class Controller extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0
    };
    this.addValue = this.addValue.bind(this);
  }
  addValue() {
    this.setState(state => ({
      value: state.value + 1
    }));
  }
  render() {
    return (
      <div>
        <button onClick={this.addValue}>Add</button>
        <OnlyEvens value={this.state.value} />
      </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode
  • Answer:
class OnlyEvens extends React.Component {
  constructor(props) {
    super(props);
  }
  shouldComponentUpdate(nextProps, nextState) {
    console.log('Should I update?');
    // Change code below this line
    if (nextProps.value % 2 === 0) {
      return true
    } else {
      return false;
    }
    // Change code above this line
  }
Enter fullscreen mode Exit fullscreen mode
  • You click the Add button and watch the order of events in your browser's console as the lifecycle hooks are triggered.

Top comments (1)

Collapse
 
bamartindev profile image
Brett Martin

Nice write up! Something else to consider is extending React.PureComponent in place of React.Component if your optimization is a shallow check of props and state, and you get the shouldComponentUpdate for free!

Check out the docs here: reactjs.org/docs/react-api.html#re...