The quickest way to set up MobX & React

MobX is a simple way to manage state in React applications. Setting it up is fairly easy – much easier than Redux – although it’s still helpful to follow a guide. For more information on MobX, check out this video.

Sidenote: React now ships with Context, which is even simpler to use than MobX. If you’re interested in that, you can see my tutorial here:

The quickest way to set up Context with React classes

  1. First, add mobx and mobx-react to your project.

    yarn add mobx mobx-react
    
  2. Then, create a directory where you can add your stores. I like to create a stores directory directly inside src.

  3. Now, create your first store. For the purposes of this guide, I’ll add a single, generic-sounding store called DataStore inside stores/dataStore.js.

    import { observable, action } from 'mobx'

    class DataStore {
    @observable data = 'supercalifragilisticexpialidocious'
    }

    export default new DataStore()
  4. Connect your store to React. Find the uppermost file in your application. This is where you render your React app to the DOM – for instance, src/index.js if you’re using create-react-app. Import your stores and wrap your application in a MobX <Provider>.

    import React from 'react'
    import ReactDOM from 'react-dom'
    import App from './App'

    // Import the MobX provider and your stores
    import { Provider } from 'mobx-react'
    import dataStore from './stores/dataStore'

    // List your stores in an object
    const stores = {
    dataStore
    }

    // Wrap your app in `<Provider {...stores}>`
    ReactDOM.render(
    <Provider {...stores}>
    <App />
    </Provider>,
    document.getElementById('root')
    )
  5. Connect your components to MobX. You can do this by @injecting your store and making the component an @observer of the state. You may also need to enable decorator support Enable decorators to make working with MobX much cleaner. and add @withRouter. If you’re using react-router-dom, your components may not update correctly unless they have a @withRouter decorator. See more here, or just use the two ‘optional’ lines included in the code from Step 5.

    import React, { Component } from 'react'
    import { withRouter } from 'react-router-dom' // optional, see Footnote 2
    import { inject, observer } from 'mobx-react'

    @inject('dataStore')
    @withRouter // optional, see Footnote 2
    @observer
    export default class ExampleComponent extends Component {
    render() {
    const { data } = this.props.dataStore
    return <div>{data}</div>
    }
    }

About the author

I'm Mark Thomas Miller, a full stack engineer and designer currently working at ConvertKit. (We're hiring!) People like Arnold Schwarzenegger, Lindsey Stirling, and Tim Ferriss use features I've built to connect with their fans. I'm currently geeking out about Svelte, mechanical keyboards, and minimalist UI design, and replaying Ocarina of Time.