Why is isMounted() an anti-pattern and what is the proper solution? in REACT

Practice



The main use case for

isMounted()

is to avoid calling

setState()

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

setState()

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

componentWillUnmount()

before unmounting.

Comments

To leave a comment

If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Lectures and tutorial on "Scripting client side JavaScript, jqvery, BackBone"

Terms: Scripting client side JavaScript, jqvery, BackBone