Green
Green

Reputation: 5000

React js componentWillUnmount for callbacks

I have read isMounted is an Antipattern and am still unsure if the codes below will cause memory leak when using with callback?

class MyComponent extends React.Component {
  componentDidMount() {
    this.mounted = true
  }
  componentWillUnmount() {
    this.mounted = false
  }
  someAPIcall() {
    callSomething(argument, (err, result) => {
      if (this.mounted === false) return
      // otherwise do something
      this.setState({...})         
    })
  }
}

Upvotes: 2

Views: 686

Answers (1)

fandro
fandro

Reputation: 4903

It's better to do that :

class MyComponent extends React.Component {
  componentDidMount() {
    someAPIcall();
  }

  someAPIcall() {
    callSomething(argument, (err, result) => {

      this.setState({...})         
    })
  }
}

Upvotes: 1

Related Questions