Connect MobX observer components to the store with the React Provider

Share this video with your friends

Social Share Links

Send Tweet
Published 8 years ago
Updated 5 years ago

Passing down stores through each layer of components can be a tedious job. This lesson demonstrates how Provider can be used to automatically connect observer based components to stores, by leveraging React's context mechanism in the background.

[00:00] As you might have noticed so far, it really doesn't matter where observable state is defined. It can be either in a model class, or it can be in our components, or in our store. For MobX, for observed components, it doesn't matter where the observables are coming from. If they are used, it will react to them.

[00:17] If you have a deeply-nested component tree, it quickly might become annoying to pass this temperature collection along each time. Luckily, React has a mechanism for that. It's called context. MobX leverages this concept to be able to pass around stores.

[00:34] If you consider our temperatures collection as a store, you could just initialize that store once, like in the root of our application. From there, we can use the provider components to pass it to any components in the component tree that is interested in the store.

[00:51] We declare that we provide temperatures. Then, in any component deeper in the tree, we can just declare that it wants temperatures. The only thing we need to do for that is providing an array of store names we are interested in.

[01:05] MobX will make sure that these store are passed into the component as a property. That is ideal for testing as well, because during testing, you can just directly pass in the stores as props to the components, while in your real component tree, those are passed down via the provider.

[01:22] In our app components, we no longer have to explicitly pass down temperatures to the temperature input. We see that everything is still working as before.

Viktor Soroka
Viktor Soroka
~ 6 years ago

You need to include Provider from MobX. At least code attached to the lecture is working for me.

Markdown supported.
Become a member to join the discussionEnroll Today