InterviewHubPRO
Section Overview
Q386

Question 386 of 445

Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

87%
React & Modern Frontend (445 Qs)•Part 11: Legacy Architecture, Migration Patterns & Historical Internals (354 - 445)

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

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

javascript
    if (this.isMounted()) {
      this.setState({...})
    }
scss
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.