componentDidUpdate vs componentDidMount

I need to make sure an input element is focused when the following is true:

  • the DOM is available and
  • properties got changed

Question: Do I need to put my code in both componentDidUpdate and componentDidMount or just componentDidUpdate would be suffice?

    private makeSureInputElementFocused() {
        if (this.props.shouldGetInputElementFocused && this.inputElement !== null) {
            this.inputElement.focus();
        }

    }

    componentDidMount() {
        this.makeSureInputElementFocused(); // <-- do i need this?
    }
    componentDidUpdate() {
        this.makeSureInputElementFocused();
    }

You have to use both.

componentDidMount()

componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.

componentDidUpdate()

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

You also could place it into the render() method which seems like it's appropriate for your case since you always want to check the focus. Then you don't need to put it into componentDidMount() and componentDidUpdate()


Each of your conditions require you to place the code inside 1 function each:

  • the DOM is available and - componentDidMount
  • properties got changed - componentDidUpdate

So you have to place inside both functions.
Another option is to call setState() inside componentDidMount, so that componentDidUpdate is invoked.