If you’ve read any of my other articles you probably know that I like React Native. Lately I spend half of my time using React Native and the other half on native Android development. When I’m using React Native usually if I need something to maintain state I turn to Redux, but I’ve been hearing more and more about MobX over the last few months so I decided to try it out recently. This article is a quick tutorial on how to create a Counter component with MobX. It assumes you have created a new project using react-native init.
To get started first you’ll want to install the mobx and mobx-react npm packages:
After that you’ll need to add in the Babel transform decorators plugin as a dev dependency so you can use decorators in your project:
You’ll also need to modify your .babelrc file so it looks like this:
Now create two new directories, one called ‘stores‘ and another called ‘components‘. Inside stores create a new file called CounterStore.js, the content should look like this:
The observable decorator is for a value/object that should be observed on changes(by a Component for example). Increase and decrease are actions(they modify the state) so you used the @action decorator. Next, make a new file called Counter.js in your ‘components‘ folder and add this to it:
The @inject decorator is used to inject a store for the Component to use, the @observer decorator is used to turn a normal Component into a reactive component. If changes are made to the store they will be reflected automatically in the Component. As you can see, the value of count from CounterStore is being used in the Text component.
Now all that’s left to do is tie all of this together. Make a new file called App.js in the root directory of your project. This is how it should look:
The Provider Component from the mobx-react package is being used. You can inject stores into your other Components by wrapping them in this. You pass store/s as props to the Provider after you’ve created them. You might also notice that the Content Component has ‘counterStore’ injected into it as well, this is so it can use the increase and decrease actions in CounterStore.
To finish off, just register the App component using AppRegistry in your entry point files(index.ios.js/index.ios.android). Here’s an example of index.ios.js:
And with that you should have a counter that you can increase/decrease using the buttons. This is what the final product will look like on iOS.
MobX feels a lot less verbose than Redux, this is probably because of the decorators. I’m definitely going to try using it in a production project soon. If you’re having any issues or are curious, you can check out the entire example project here. If you’re interested in persisting state over sessions after doing this tutorial, you should definitely check out mobx-persist.