Search code examples
reactjsreact-componentreact-lifecycle

Why component update lifecycle executes whenever parent's state changes?


I have a parent component called 'App' in which a child component is used called 'NewComp'.I have defined componentDidUpdate() lifecycle inside child component,not in parent component.

Parent component:

class App extends Component {

    state = {
      count:0,
    }

    change = () =>{
      this.setState({
        count:this.state.count+1,
      })
    }

    render() {

      return (
        <div>
          <p>Count = {this.state.count}</p>
          <button onClick={this.change}>Add Count</button>
          <NewComp />
        </div>
      );
    }
}

Child Component:

export default class NewComp extends Component {

  componentDidUpdate(){
    console.log('Child component did update');
  }

  render() {
    return (
      <div>
        <h1>Child Component</h1>
      </div>
    )
  }
}

Now every time I change parent state by 'Add Count' button ,the componentDidMount() in child component executes even there is no change in child component


Solution

  • Parent component is triggered re-render, and in your NewComp, shouldComponentUpdate alway return true by default, so NewComp is triggered re-render as well. You can avoid it by implementing shouldComponentUpdate in NewComp or use PureComponent:

    export default class NewComp extends PureComponent {
    
      componentDidUpdate(){
        console.log('Child component did update');
      }
    
      render() {
        return (
          <div>
            <h1>Child Component</h1>
          </div>
        )
      }
    }