user768861
user768861

Reputation: 83

Is componentDidUpdate for the parent called when a child components state changes?

I think the answer is no but I just wanted to confirm. In order to call componentDidUpdate on the parent we'd have to update the parents state right? Merely updating the childrens state is not enough right?

Thanks in advance.

Upvotes: 0

Views: 495

Answers (1)

Brian Thompson
Brian Thompson

Reputation: 14365

Easiest way to know is to try it out...

Here you can see that: No, it will not call the parent's componentDidUpdate unless the state of the parent (or it's parent) changes.

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: 'parent' }
  }
  
  componentDidUpdate() {
    console.log('Parent Updated');
  }
  
  onChange = (e) => {
    this.setState({ value: e.target.value });
  }
  
  render() {
    return <Child value={this.state.value} onChange={this.onChange} />
  }
}

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = { value: 'child' }
  }
  
  componentDidUpdate() {
    console.log('Child Updated');
  }
  
  onChange = (e) => {
    this.setState({ value: e.target.value });
  }
  
  render() {
    return (
      <div>
        <div>
          <input value={this.props.value} onChange={this.props.onChange} />
        </div>
        <div>
          <input value={this.state.value} onChange={this.onChange} />
        </div>
      </div>
     );
  }
}


ReactDOM.render(<Parent />, document.getElementById('react'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"/>

Upvotes: 1

Related Questions