DanielN DanielN - 4 months ago 29
Javascript Question

What is the main difference between Mobx.inject an Mobx.observer when connecting stores?

I am beginning to connect my store to mobx.
I wonder the difference between the use of

observer(['store'],...)
or the use of
inject('store')(observer(...))


The main difference I see it that inject is not reactive. So what the intents of inject over observer exactly?

Answer

There is no difference between observer(['store'], Component) and inject('store')(observer(Component)).

observer decorator checks if the first argument is an array. If it is an array then it invokes inject internally.

function observer(arg1, arg2) {
...
 if (Array.isArray(arg1)) {
   ...
   return inject.apply(null, arg1)(observer(arg2));
  }
...

However, you can add more decorators between inject and observer. In that case, there will be a difference: intermediate decorators would have access to injected props. Outer decorators, obviously, won't have access to injected props if you do not use inject.

inject is simply a convenient way to inject props since MobX already had the mechanism to pass stuff in context. Before you would have to use another library (react-tunnel for example) if you wanted to inject props to a component without turning it into a reactive component.

Comments