Skip to content
This repository has been archived by the owner on Dec 31, 2020. It is now read-only.

Is autorun equivalent to componentWillReact? #62

Closed
mdebbar opened this issue Jun 6, 2016 · 4 comments
Closed

Is autorun equivalent to componentWillReact? #62

mdebbar opened this issue Jun 6, 2016 · 4 comments

Comments

@mdebbar
Copy link

mdebbar commented Jun 6, 2016

I'm excited about MobX. I was able to reduce the code size significantly by switching from Redux to MobX. Thanks for the great library!

One of the things I usually need in my components is to do some logic whenever a certain prop has changed. Previously, I used to do that logic in componentDidMount and in componentWillReceiveProps. But now I have another source of data: MobX store. Changes happening to mobx data don't trigger componentWillReceiveProps but instead componentWillReact. So now I need to do that logic in componentWillReact as well.

To reduce the number of lifecycle methods I use, I thought of doing:

componentDidMount() {
  autorun(() => this.thatLogic());
}

Is the above equivalent to:

componentDidMount() {
  this.thatLogic();
}
componentWillReact() {
  this.thatLogic();
}

?

My guess is that the autorun solution is even better because it re-triggers the logic based on changes in the data that the logic cares about. As opposed to the latter which re-triggers the logic based on changes in data that the render cares about. Am I correct?

@mweststrate
Copy link
Member

Personally I find it quite naturally to react to prop changes. But so far I didn't need to react to other observables (besides rendering of course) in a component. Usually I put that kind of logic in a store / controller. Nonetheless the autorun solution is fine. Don't forget to dispose it on componentWillUnmount!

@mdebbar
Copy link
Author

mdebbar commented Jun 7, 2016

Oh thanks for reminding me to dispose of the autorun. I completely forgot about that.

@mdebbar mdebbar closed this as completed Jun 7, 2016
@sanyamagrawal
Copy link

@mweststrate : A quick Question , how do i dispose an autorun/reaction in componentWillUnmount?

componentWillMount() {
reaction(
() => this.props.aggregateStore.filters,
this.fetchData
);
}

How do I dispose this in componentWillUnmount?

@mweststrate
Copy link
Member

mweststrate commented Mar 1, 2018 via email

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants