React shouldComponentUpdate() Method

React 组件生命周期React Component Lifecycle

The shouldComponentUpdate() method format is as follows:

shouldComponentUpdate(nextProps, nextState)

shouldComponentUpdate() returns a boolean value that specifies whether React should continue rendering. The default value istrue, i.e.statethe component will re-render every time a change occurs.

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

The following example demonstrates the behavior when the shouldComponentUpdate() method returns false (clicking the button will not modify it):

Example

class Header extends React.Component { constructor(props) { super(props); this.state = {favoritesite: "example"}; } 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> ); } }

Try it »

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

Example

class Header extends React.Component { constructor(props) { super(props); this.state = {favoritesite: "example"}; } 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> ); } }

Try it »

React 组件生命周期React Component Lifecycle

Other Extensions