Easy Tutorial
❮ React Forms Events React Ref Getderivedstatefromprops ❯

React shouldComponentUpdate() Method

React Component Lifecycle

The shouldComponentUpdate() method has the following format:

shouldComponentUpdate(nextProps, nextState)

The shouldComponentUpdate() method returns a boolean value that specifies whether React should continue rendering. The default value is true, meaning that every time the state changes, the component re-renders.

The return value of shouldComponentUpdate() is used to determine whether the output of a React component is affected by the current state or props changes. When props or state change, shouldComponentUpdate() is called before rendering.

The following example demonstrates the behavior when shouldComponentUpdate() returns false (the button click does not modify):

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritesite: "tutorialpro"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeSite = () => {
    this.setState({favoritesite: "google"});
  }
  render() {
    return (
      <div>
      <h1>My favorite website is {this.state.favoritesite}</h1>
      &lt;button type="button" onClick={this.changeSite}>Modify</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

The following example demonstrates the behavior when shouldComponentUpdate() returns true (the button click can modify):

Example

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritesite: "tutorialpro"};
  }
  shouldComponentUpdate() {
    return true;
  }
  changeSite = () => {
    this.setState({favoritesite: "google"});
  }
  render() {
    return (
      <div>
      <h1>My favorite website is {this.state.favoritesite}</h1>
      &lt;button type="button" onClick={this.changeSite}>Modify</button>
      </div>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));

React Component Lifecycle

❮ React Forms Events React Ref Getderivedstatefromprops ❯