Does the componentDidUpdate run after all children have been updated?

I would like to know if the lifecycle method of a React component will execute componentDidUpdate

after all child methods have finished render

or immediately after a method has been called render

on that component.

Since it is recursively recursively calling the method render

to update the view, I have a hunch what componentDidUpdate

is executed after all the component's children have been re-rendered, but the information is in the documentation . When exactly is it called componentDidUpdate

?

+3


source to share


2 answers


The method componentDidUpdate

is called after the render

component method is executed . This means that it will be called after all the child methods have finished render

. This is implied in the documentation you provided:

Use this as an opportunity to work with the DOM when the component has been updated.



The component is only updated after rendering, so the documentation implies that it is called after all the children, and thus the parent, have finished re-rendering (although a bit unclear ). You can only really work with the DOM when the update finishes, children and that's it.

For example, let's say we have two components, A

and B

and B

displays the component A

. componentDidUpdate

for B

will only be called once B

render

. render

of B

will complete after being A

render

called successfully, because the children are rendered first due to being part of the parent. This means that the answer to your question is: componentDidUpdate

is executed after all children have finished render

.

+5


source


Not sure if there is more detailed documentation somewhere, but it's really easy enough to check it yourself.

class Nested extends React.Component {
  constructor(props){
    super(props);
    this.state = {foo: undefined};
  }
  render() {
    console.log("Rendered " + this.props.name);
    return <div><button onClick={() => {this.setState({foo: Date.now()})}}>Update {this.props.name}</button>{this.props.children ? React.cloneElement(React.Children.only(this.props.children), {foo: this.state.foo}) : undefined}</div>
  }
  componentDidUpdate() {
    console.log("Updated " + this.props.name);
  }
}

ReactDOM.render(<Nested name="outer"><Nested name="inner"></Nested></Nested>, document.getElementById("app"));

      

http://jsbin.com/yiyuhegayo/edit?js,console,output



Updating the outer component causes the innermost component to run componentDidUpdate

, then the outermost one. Updating an internal component only forces that component to update.

Interestingly, this is the opposite for functions render

. The outer component displays first, then the inner one.

+3


source







All Articles