7

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?

dagda1
  • 26,856
  • 59
  • 237
  • 450

4 Answers4

6

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)

mweststrate
  • 4,890
  • 1
  • 16
  • 26
  • 6
    I went through your article, but it basically describes the conceptual model, not under the hood workings of mobx (i.e. at JavaScript level). For eg, how does any `observer` component gets notified of changes to `observable`s? Does it use an event based system? Can you mention the pseudo code for that? – darKnight May 16 '18 at 17:36
4

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.

Asur
  • 1,949
  • 4
  • 23
  • 41
2

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.

Lokii
  • 402
  • 4
  • 14
0

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/.

Stephan Rauh
  • 3,069
  • 2
  • 18
  • 37