In this article you will get to know how your life as React developer could be easier if you simply switch to MobX from Redux.
With the introduction of React-Context and increasing use of MobX in react application, I really hope that one day Redux bubble bursts.
All of that being said, let’s begin with creating a simple counter example in reactjs with a little help from MobX.
First install MobX and supporting MobX React library
npm install mobx
npm install mobx-react
Create a store file call it Store.js
import { action, computed, observable } from 'mobx';
class CounterStore {
@observable counter = 0;
@action.bound
incCount() {
this.counter += 1;
}
@action.bound
decCount() {
this.counter -= 1;
}
@action.bound
resetCount() {
this.counter = 0;
}
@computed get multiplyCounter(){
return this.counter*this.counter;
}
}
export default CounterStore;
A brief explanation on the decorators used in above store.
@observable : Variable decorator used to declare a variable that needs to be tracked by MobX.
@action.bound : Method decorator used to update observables declared in the store.
@computed : Method decorator used to do calculation on the observable and return computed value.
The store needs to be passed as prop to the start component in this case <App/> doing so store would be available in all its child components for use as a inherited prop.
Well there is an additional step that you need to do to access MobX store in component and thats is decorating component with @observer decorator from ‘mobx-react’ library.
App.js
import React, { Component } from "react";
import ReactDOM from "react-dom";
import CounterStore from "./store";
import { observer } from 'mobx-react';
@observer class App extends Component {
render() {
return (
<div>
<div>Count:{this.props.store.counter}</div>
<div>
<button onClick={this.props.store.incCount}> Count +</button>
<button onClick={this.props.store.decCount}> Count -</button>
<button onClick={this.props.store.resetCount}> Reset</button>
</div>
<div>
Multiplied Counter: {this.props.store.multiplyCounter}
</div>
</div>
);
}
};
const store = new CounterStore();
ReactDOM.render(<App store={store} />, document.querySelector("#root"));
Done your store is ready to be used.
Its as simple as it can get !!
Side note in case you are facing issue with adding decorators to your code, you would need to add below plugins in your .babelrc file
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
[
"@babel/plugin-proposal-decorators",
{
"legacy": true
}
],
[
"@babel/plugin-proposal-class-properties",
{
"loose": true
}
]
]
}