Reputation: 28820
I am curious as to how mobx works under the hood.
If I have a component that is both an observer and contains observables:
@observer
export default class Form extends Component {
@observable submitted = false;
@action.bound
submit() {
}
}
How does mobx cause a re-render without using setState or does it use setState?
Upvotes: 8
Views: 2416
Reputation: 2057
To understand how mobx
works under the hood, check this repl out.
I learned about it from one of the videos of @mweststrate and an academic paper from someone. Both of which I cannot find anymore.
Upvotes: 3
Reputation: 492
In my understanding, mobx defines its observable properties on stores something like this:
export const nameObservable = new Observable(observer => {
Object.defineProperty(customState, "firstName", {
get: function() {
return this._firstName.toUpperCase();
},
set: function(name) {
this._firstName = name;
observer.next(this._firstName);
}
});
});
// In your component
nameObservable.subscribe(render)
When you execute customState.firstName = 'New name'
this will call the set method on property and observer.next
will trigger all methods subscribed to this property... causing update in UI.
Upvotes: 3
Reputation: 3120
MobX uses Object.defineProperty()
to wrap it's own functionality to the assigment operator. When you write something like form.submitted = false
, in reality a MobX method is called. Also see https://twitter.com/dan_abramov/status/741633922694586368 and https://x-team.com/blog/es5-object-defineproperty-method/.
Upvotes: 0
Reputation: 4978
See: https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254. @observer
is basically a shorthand for autorun(() => this.render())
(it is actually a bit more complex, but that is what it conceptualy boils down to)
Upvotes: 7