React shouldComponentUpdate() Method
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>
<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>
<button type="button" onClick={this.changeSite}>Modify</button>
</div>
);
}
}
ReactDOM.render(<Header />, document.getElementById('root'));