Search code examples
reactjsredux-thunk

Should React component method reference be cleared in component unmount?


lets assume something lile this:

handleClick = () => {
  dispatchThunkAction(this.someMethod),
}

someMethod = () => {
  //do something
}

dispatchThunkAction fires http request. once done, thunk action calls back someMethod thats passed to it.

should someMethod be set to null in componentWiUnmount for the case unmount happens in the middle of http (or any other async operation) call?

so, like

componentWillUnmount() {
  this.someMethod = null;
}

so that garbage collector knows it can pick it up immediately.


Solution

  • Setting the method to null will not help, but you could create an instance variable called e.g. _isMounted that you set to false in componentDidUnmount and check that this variable is true before you do anything in someMethod.

    class App extends React.Component {
      _isMounted = true
    
      handleClick = () => {
        dispatchThunkAction(this.someMethod)
      }
    
      someMethod = () => {
        if (!this._isMounted) {
          return
        }
    
        //do something
      }
    
      componentDidUnmount() {
        this._isMounted = false
      }  
    
      // ...
    }