Recently, we decided to move from using React's context functionality directly, to using MobX's Provider feature. Updating the code was a little painful, but not nearly as hard as trying to move from React Router v2 to v4! There were a few things that were hard in particular, such as updating all of the Enzyme-based tests. If you need to do the same thing, here are some tips:
First of all, start by reading all the documentation on Provider and inject. I'm not going to duplicate that here.
Let's suppose you have a component named MyComponent, and you have a MobX store named myStore.
If you're using a function-based component like:
Then to set the propTypes, you'll need to write:
Thankfully, you'll get a warning if you get this one wrong.
In this case, the class-based syntax with decorators looks a bit nicer:
If you're using shallow to test MyComponent, then you should use .wrappedComponent, and pass myStore as a prop directly (which is one of my favorite features of how Provider works):
If you're using mount, don't use wrappedComponent. Instead use Provider:
If you're using mount, and you see some code like:
You'll probably need to change it to:
If you are in a weird situation where you have to use context and Provider, you're going to find out that Enzyme won't pass any context to Provider since Provider isn't expecting it. Hence, nested components won't get the context that they need. To work around that problem (which is really a problem with how Enzyme works), you can do something like:
Anyway, that's all I have for now. I'll keep updating this blog post with more tips as I find them.