0 votes
in ReactJS by
Why is isMounted() an anti-pattern and what is the proper solution?

1 Answer

0 votes
by

The primary use case for isMounted() is to avoid calling setState() after a component has been unmounted, because it will emit a warning.

if (this.isMounted()) {

  this.setState({...})

}

Checking isMounted() before calling setState() does eliminate the warning, but it also defeats the purpose of the warning. Using isMounted() is a code smell because the only reason you would check is because you think you might be holding a reference after the component has unmounted.

An optimal solution would be to find places where setState() might be called after a component has unmounted, and fix them. Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted before the data arrives. Ideally, any callbacks should be canceled in componentWillUnmount(), prior to unmounting.

Related questions

0 votes
asked Feb 12, 2022 in OWASP Top 10 Vulnerabilities by DavidAnderson
0 votes
asked May 17, 2019 in Other by Derya
...