React shouldComponentUpdate() method


Release date:2024-03-14 Update date:2024-03-15 Editor:admin View counts:160

Label:

React shouldComponentUpdate() method

The shouldComponentUpdate() format of the method is as follows:

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate() method returns a Boolean value that specifies whether React should continue rendering. The default value is true thatis, state the component is re-rendered each time it changes.

shouldComponentUpdate() is used to determine whether the output of the React component is affected by the current state or props the impact of the change, when props or state when there is a change shouldComponentUpdate() will be called before the rendering is executed.

The following example demonstrates shouldComponentUpdate() method returns false the action performed when (cannot be modified by clickingthe button):

Example

classHeaderextendsReact.Component{constructor(props){super(props);this.state={favoritesite:"runoob"};}shouldComponentUpdate(){returnfalse;}changeSite=()=>{this.setState({favoritesite:"google"});}render(){return(<div>
<h1>My favorite website is{this.state.favoritesite}</h1>
<buttontype="button"onClick={this.changeSite}>modify</button>
</div>);}}ReactDOM.render(<Header/>,document.getElementById('root'));

The following example demonstrates shouldComponentUpdate() method returns true (click the button to modify it):

Example

classHeaderextendsReact.Component{constructor(props){super(props);this.state={favoritesite:"runoob"};}shouldComponentUpdate(){returntrue;}changeSite=()=>{this.setState({favoritesite:"google"});}render(){return(<div>
<h1>My favorite website is{this.state.favoritesite}</h1>
<buttontype="button"onClick={this.changeSite}>modify</button>
</div>);}}ReactDOM.render(<Header/>,document.getElementById('root'));

Powered by TorCMS (https://github.com/bukun/TorCMS).