The shouldComponentUpdate Method -
The shouldComponentUpdate() method is invoked before rendering (render method) when new props or state are being received.
The defaults value is true.
The shouldComponentUpdate() method is not called for the initial render or when forceUpdate() is used.
Explore to Understand - React Lifecycle Components
As an Example 1–
When shouldComponentUpdate value is fale? My Color is red after click on Change color.
import React from 'react';
import ReactDOM from 'react-dom';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {color: "red"};
}
shouldComponentUpdate() {
return false;
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My Color is {this.state.color}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Result of this example is – My color is red
As an Example 2–
When shouldComponentUpdate value is true? My Color is blue after click on Change color.
import React from 'react';
import ReactDOM from 'react-dom';
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {color: "red"};
}
shouldComponentUpdate() {
return true;
}
changeColor = () => {
this.setState({color: "blue"});
}
render() {
return (
<div>
<h1>My Color is {this.state.color}</h1>
<button type="button" onClick={this.changeColor}>Change color</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));
Result of this example is – My color is blue