Will componentDidMount always be called before componentWillUnmount?

Viewed 85

Is it guaranteed that the componentDidMount lifecycle method will always be executed (and complete) before componentWillUnmount?

For example, in my componentDidMount method I am registering a subscription:

componentDidMount() {
    this.unsubscribe = subscribe();
}

componentWillUnmount() {
    this.unsubscribe();
}

If componentDidMount is not guaranteed to execute and complete before componentWillUnmount then this.unsubscribe is potentially undefined and attempting to invoke it will throw a runtime error.

1 Answers

React class component documentation about componentDidMount lifecycle method (https://reactjs.org/docs/react-component.html#componentdidmount) states:

This is a good place to set up any subscriptions. If you do that, don’t forget to unsubscribe in componentWillUnmount().

Based on this, I would say it is guaranteed that componentDidMount will always be executed before componentWillUnmount, as otherwise most of the unsubscriptions would throw the error you mention.

Related