Practice
The main use case for
is to avoid calling
after a component has been unmounted, since doing so will produce a warning.
if (this.isMounted()) {
this.setState({...})
}
Checking isMounted()
before calling setState() does get rid of the warning, but it also defeats the purpose of the warning. Using isMounted() is a code smell, because the only reason you would need to check it is that you think you might be holding a reference after the component has been unmounted.
The best solution is to find the places where
could be called after the component is unmounted and fix them. Such situations most often arise from callbacks, when a component is waiting on some data and gets unmounted before that data arrives. Ideally, any callbacks should be cancelled in
before unmounting.
Comments