ScanSkill

shouldComponentUpdate()

The shouldComponentUpdate() method returns a Boolean value that specifies whether or not React should continue with the rendering or not. The default value is true.

Syntax

 shouldComponentUpdate() {
    return true/false;
  }

Example

class Example extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "John"};
  }
  shouldComponentUpdate() {
    return false;
  }
  changeName = () => {
    console.log("click");
    this.setState({name: "Billy"});
  }
  render() {
    return (
      <div>
      <h1>My name is {this.state.name}</h1>
      <button type="button" onClick={this.changeName}>Change Name</button>
      </div>
    );
  }
}
shouldComponentUpdate

As we can see, The changeName() function is triggered but the component is not updated because the shouldComponentUpdate() is set to false which prevents the component from updating.

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {name: "John"};
  }
  shouldComponentUpdate() {
    return true;
  }
  changeName = () => {
    console.log("click");
    this.setState({name: "Billy"});
  }
  render() {
    return (
      <div>
      <h1>My name is {this.state.name}</h1>
      <button type="button" onClick={this.changeName}>Change Name</button>
      </div>
    );
  }
}
shouldComponentUpdate

Here, the shouldComponentUpdate() is set to true. So when the changeName() function is triggered the component is also updated with a new state value.