8 ms·
A while back I was building a large application for an internal team at my company. It got to the point where local state was just not solving all of my proble
by Phillips126 7y ago
A while back I was building a large application for an internal team at my company. It got to the point where local state was just not solving all of my problems so I started to explore Redux. I had been creating React apps for several years but I could not wrap my head around Redux - it was far too much complexity adding all sorts of actions, reducers, boilerplate, etc. I started looking for alternatives and stumbled upon Mobx which I liked much better and have been using ever since.
Mobx-react[0] felt like much less work with virtually the same outcome. You create a single (or multiple stores), pass it into your app with a
<Provider Store={store}>
<App />
</Provider>
and you are off to the races. When adding the global state to a component, it was super easy:
export default inject('Store')(observer(MyComponent))
Or use decorators (requires ejecting create-react-app or modifying the webpack configuration settings):
@inject('Store')
@observer
class MyComponent extends Component {...}
export default MyComponent
Accessing the store:
const {myValues} = this.props.Store
In the store you organize your code by observables (global variables), actions (functions that modify observables) or computed (highly optimized functions that return values derived from state). I treat it as a "source of truth" in a single file.
import {observable, action, computed, decorate} from "mobx"
class Store {
// Observables
myValues = [0, 1, 2, 3, 4]
// Actions
addValue = num => myValues.push(num)
// Computed
get getTotal() {
return myValues.reduce((total, cur) => total + cur)
}
}
decorate(Store, {
myValues: observable,
addValue: action,
getTotal: computed
})
const store = new Store()
export default store
In the end I felt that my code was far more readable and maintainable but your miles may vary.
Here is a relatively simple example of how to use mobx-react demonstrating an observable, action, and computed: https://www.codementor.io/susanadelokiki/managing-state-with-mobx-iqax3wp63 https://www.codementor.io/susanadelokiki/managing-state-with...
[0] https://github.com/mobxjs/mobx-react https://github.com/mobxjs/mobx-react
- amoerie 7y agoI can attest to the genius that is MobX. Having worked on a frontend project built with RxJs + React for nearly two years, I feel like I have kept all of the benefits of reactivity and discarded a lot of complexity and learning curve that mostly came from RxJs. The API surface of MobX is a breeze, and it kind of pushes you into the pit of success.