The quickest way to set up MobX & React

August 14, 2018

MobX is a breath of fresh air in state management for React applications. Setting it up is fairly simple – much simpler than Redux – although it’s still helpful to follow a guide. For more information on MobX, check out this video.

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 support1 and add @withRouter2.

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>
  }
}
  1. Enable decorators to make working with MobX much cleaner↩︎

  2. 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. ↩︎