Iñaki Baz Castillo Iñaki Baz Castillo - 1 year ago 229
React JSX Question

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?

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
by setting
this._mounted = false
and so on, but I don't like adding private state if not needed.

Answer Source

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() {

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download