简体   繁体   中英

Why does React component update if props and state didn't change

A React Copmponent is rendering when its state or propr remain the same. I don't get why it does it rerender/update since the result wouldn't change

class A extends Component {
  render() {
    console.log("Hello")
    return "Foo";
  }
}
class App extends Component {
  constructor(props) {
    super(props);

    this.state = { a: "ASDA" };
  }

  render() {
    return (
      <div>
        <button onClick={()=>this.setState({a: Math.random()}) }>asdsa</button>
        <div>{this.state.a}</div>
        <A />
      </div>
    );
  }

Whenever I click the button, component A is rerendered (I can see "hello" in the console) I thought React was avoiding many useless rerenderings.

Your parent component is re-rendering because its state changes.

When a component re-renders, all its children are re-rendered. This means that the render function runs, and the result is added to the virtual DOM.

This result is then compared with the existing DOM. It doesn't mean that that actual DOM changes for the child components, just that they are re-evaluated because the DOM might need to change.

If it turns out that the child element does need to change, then that element in the actual DOM is re-rendered. If the child element doesn't need to change, that element in the DOM remains un-effected.

This is generally fine and has minimal to no performance impacts for small components, so usually you don't need to worry about it.

If you have deep component hierarchies or components with complex render functions that perform computationally expensive operations, consider using React.memo if you feel that the render cycle is causing a hit on performance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM