Store injecting

The store injection pattern was popularized by the mobx-react library. It refers to a now obsolete way of accessing the MobX stores across the component tree. It was introduced because the React legacy context was rather awkward to use.

We are in 2019 now and we don't need injections anymore (kids, don't do drugs).

Continue reading the Migration guide to learn more about how to abandon the inject paradigm.

Why is it obsolete?

The main reason is that we have much better tools at our disposal now. The inject pattern is not wrong or broken in general, but it is rather limited and error-prone.

In its simplest form inject('myStore') (strings, meh!) the wrapped component props get modified and it's easy to lose track of what's coming into the component because the string argument does not give you any clue. This can be a source of annoying bugs, and maybe more importantly the pattern is incompatible with a typed language like Typescript. You can read more about the struggles with Typescript in this unresolved issue.

An alternative variant of inject allows for reactive selections over the stores to pick the values that the component requires. It can be useful if reused over multiple components, but otherwise it brings similar confusion as the simple form of inject.

2019-12-20 07:29:59 星期五

  1. const NameDisplayer = ({ name }) => <h1>{name}</h1>
  2. const UserNameDisplayer = inject(stores => ({
  3. name: stores.userStore.name,
  4. }))(NameDisplayer)
  5. const App = () => <UserNameDisplayer name="Is this name used? Who knows." />