2

I am learning reactJs, after reading this part of the docs:

An easy migration strategy for anyone upgrading their code to avoid isMounted() is to track the mounted status yourself. Just set a _isMounted property to true in componentDidMount and set it to false in componentWillUnmount, and use this variable to check your component's status.

Does that mean the _isMounted value has to be stored in state?

I have this so far:

isMounted: function(){
    this.setState({ _isMounted: true });
},

componentDidMount: function() {
    if(this.state._isMounted) {  // This is bad.
        this.setState({...});
    }
},
lux
  • 8,315
  • 7
  • 36
  • 49
Bomber
  • 10,195
  • 24
  • 90
  • 167
  • I actually disagree with the accepted answer and think it means, set it like `this._isMounted = true` in didMount and `... = false` in willUnmount, and then check it where you need to with `if (this._isMounted)` – TKoL Mar 05 '18 at 15:00
  • @TKoL That won't work: https://codesandbox.io/s/epic-forest-4lf7i – lux Nov 21 '19 at 18:58

2 Answers2

2

Yes, you can track _isMounted in state, since:

  1. It cannot be computed from props
  2. You will most likely use it in render()

Via https://twitter.com/dan_abramov/status/749710501916139520

Example

http://codepen.io/mikechabot/pen/GqvyOE

SomeComponent.jsx

class SomeComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      _isMounted: false
    }
  }
  componentDidMount() {
    this.setState({
      _isMounted: true
    })
  }
  render() {
    const { _isMounted } = this.state;
    return (
      <div>
        Mounted? { _isMounted ? 'Yes' : 'No' }
      </div>
    )
  }
}
lux
  • 8,315
  • 7
  • 36
  • 49
0

I was wondering how to work around this antipattern as well and ended up using the accepted answer from lux.

It later turns out using state is just as bad and even causes double render.

The intended antipattern work around is forex:

class MyComponent extends React.Component {

    constructor(props) {
        super(props);
        this._isMounted = undefined;
    }

    componentDidMount() {
        this._isMounted = true;
    }

    componentWillUnmount() {
      this._isMounted = false;
    }
}
imiro
  • 167
  • 7
  • This won't work: https://codesandbox.io/s/epic-forest-4lf7i It will only log undefined in `render()` – lux Nov 21 '19 at 18:58
  • That wont yes, since the lifecycle methods arent executed before render. – imiro Nov 23 '19 at 01:02