reactjs: is there public API to check if the component is mounted/unmounted

Basically I would like to have this within a component:

setTimeout(() =>
{
  if (this.isMounted())  // NOTE: this does not exist
    setState({ foo: 123 });
}, 5000);

But there is no API for that, am I wrong?

Calling setState() on an unmounted components is considered an error (and logged such one by React when in development mode).

Of course, I could set my own state in componentWillUnmount() by setting this._mounted = false and so on, but I don't like adding private state if not needed.

Upvotes: 4

Views: 1691

Answers (1)

Waiski
Waiski

Reputation: 9680

While this is the exact scenario isMounted() was originally created for, the current recommendation the usage of isMounted() is bad and will be removed in future React versions.

Instead, you should just check that any asynchrous functions are properly cancelled upon unmounting the component. If you use setTimeout, it's easy enough to just save the timeout identifier and cancel it in componentWillUnmount:

this.timeout = setTimeout(() => {
  this.setState({ foo: 123 });
}, 5000);

...

componentWillUnmount() {
  clearTimeout(this.timeout)
}

So to answer your question, there is no and there should be no API for checking if a component is mounted. This is because when unmounted, all references to the component should be cleared so that the garbage collector may remove it from memory.

Upvotes: 3

Related Questions