Comment

Comment by Phillips126

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...

[0] https://github.com/mobxjs/mobx-react

parent Phillips126 7 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton