mobx-react
🚨🚨🚨 This repo has been moved to mobx

Package with React component wrapper for combining React with MobX.
Exports the observer decorator and other utilities.
For documentation, see the MobX project.
There is also work-in-progress user guide for additional information.
This package supports both React and React Native.
Choosing your version
There are currently two actively maintained versions of mobx-react:
| NPM Version |
Support MobX version |
Supported React versions |
Supports hook based components |
| v7 |
6.* |
16.8+ |
Yes |
| v6 |
4._ / 5._ |
16.8+ |
Yes |
| v5 |
4._ / 5._ |
0.13+ |
No, but it is possible to use <Observer> sections inside hook based components |
mobx-react 6 / 7 is a repackage of the smaller mobx-react-lite package + following features from the mobx-react@5 package added:
- Support for class based components for
observer and @observer
Provider / inject to pass stores around (but consider to use React.createContext instead)
PropTypes to describe observable based property checkers (but consider to use TypeScript instead)
- The
disposeOnUnmount utility / decorator to easily clean up resources such as reactions created in your class based components.
Installation
npm install mobx-react --save
Or CDN: https://unpkg.com/mobx-react (UMD namespace: mobxReact)
import { observer } from "mobx-react"
This package provides the bindings for MobX and React.
See the official documentation for how to get started.
For greenfield projects you might want to consider to use mobx-react-lite, if you intend to only use function based components. React.createContext can be used to pass stores around.
API documentation
Please check mobx.js.org for the general documentation. The documentation below highlights some specifics.
observer(component)
Function (and decorator) that converts a React component definition, React component class, or stand-alone render function, into a reactive component. A converted component will track which observables are used by its effective render and automatically re-render the component when one of these values changes.
Functional Components
React.memo is automatically applied to functional components provided to observer. observer does not accept a functional component already wrapped in React.memo, or an observer, in order to avoid consequences that might arise as a result of wrapping it twice.
Class Components
When using component classes, this.props and this.state will be made observables, so the component will react to all changes in props and state that are used by render.
shouldComponentUpdate is not supported. As such, it is recommended that class components extend React.PureComponent. The observer will automatically patch non-pure class components with an internal implementation of React.PureComponent if necessary.
See the MobX documentation for more details.
import { observer } from "mobx-react"
// ---- ES6 syntax ----
const TodoView = observer(
class TodoView extends React.Component {
render() {
return <div>{this.props.todo.title}</div>
}
}
)
// ---- ESNext syntax with decorator syntax enabled ----
@observer
class TodoView extends React.Component {
render() {
return <div>{this.props.todo.title}</div>
}
}
// ---- or just use function components: ----
const TodoView = observer(({ todo }) => <div>{todo.title}</div>)
Observer
Observer is a React component, which applies observer to an anonymous region in your component.
It takes as children a single, argumentless function which should return exactly one React component.
The rendering in the function will be tracked and automatically re-rendered when needed.
This can come in handy when needing to pass render function to external components (for example the React Native listview), or if you
dislike the observer decorator / function.
class App extends React.Component {
render() {
return (
<div>
{this.props.person.name}
<Observer>{() => <div>{this.props.person.name}</div>}</Observer>
</div>
)
}
}
const person = observable({ name: "John" })
ReactDOM.render(<App person={person} />, document.body)
person.name = "Mike" // will cause the Observer region to re-render
In case you are a fan of render props, you can use that instead of children. Be advised, that you cannot use both approaches at once, children have a precedence.
Example
class App extends React.Component {
render() {
return (
<div>
{this.props.person.name}
<Observer render={() => <div>{this.props.person.name}</div>} />
</div>
)
}
}
const person = observable({ name: "John" })
ReactDOM.render(<App person={person} />, document.body)
person.name = "Mike" // will cause the Observer region to re-render
useLocalObservable hook
User guide
Local observable state can be introduced by using the useLocalObservable hook, that runs once to create an observable store. A quick example would be:
import { useLocalObservable, Observer } from "mobx-react-lite"
const Todo = () => {
const todo = useLocalObservable(() => ({
title: "Test",
done: true,
toggle() {
this.done = !this.done
}
}))
return (
<Observer>
{() => (
<h1 onClick={todo.toggle}>
{todo.title} {todo.done ? "[DONE]" : "[TODO]"}
</h1>
)}
</Observer>
)
}
When using useLocalObservable, all properties of the returned object will be made observable automatically, getters will be turned into computed properties, and methods will be bound to the store and apply mobx transactions automatically. If new class instances are returned from the initializer, they will be kept as is.
It is important to realize that the store is created only once! It is not possible to specify dependencies to force re-creation, nor should you directly be referring to props for the initializer function, as changes in those won't propagate.
Instead, if your store needs to refer to props (or useState based local state), the useLocalObservable should be combined with the useAsObservableSource hook, see below.
Note that in many cases it is possible to extract the initializer function to a function outside the component definition. Which makes it possible to test the store itself in a more straight-forward manner, and avoids creating the initializer closure on each re-render.
Note: using useLocalObservable is mostly beneficial for really complex local state, or to obtain more uniform code base. Note that using a local store might conflict with future React features like concurrent rendering.
Server Side Rendering with enableStaticRendering
When using server side rendering, normal lifecycle hooks of React components are not fired, as the components are rendered only once.
Since components are never unmounted, observer components would in this case leak memory when being rendered server side.
To avoid leaking memory, call enableStaticRendering(true) when using server side rendering.
import { enableStaticRendering } from "mobx-react"
enableStaticRendering(true)
This makes sure the component won't try to react to any future data changes.
Which components should be marked with observer?
The simple rule of thumb is: all components that render observable data.
If you don't want to mark a component as observer, for example to reduce the dependencies of a generic component package, make sure you only pass it plain data.
Enabling decorators (optional)
Decorators are currently a stage-2 ESNext feature. How to enable them is documented here.
Should I still use smart and dumb components?
See this thread.
TL;DR: the conceptual distinction makes a lot of sense when using MobX as well, but use observer on all components.
PropTypes
MobX-react provides the following additional PropTypes which can be used to validate against MobX structures:
observableArray
observableArrayOf(React.PropTypes.number)
observableMap
observableObject
arrayOrObservableArray
arrayOrObservableArrayOf(React.PropTypes.number)
objectOrObservableObject
Use import { PropTypes } from "mobx-react" to import them, then use for example PropTypes.observableArray
Provider and inject
See also the migration guide to React Hooks.
Note: usually there is no need anymore to use Provider / inject in new code bases; most of its features are now covered by React.createContext.
Provider is a component that can pass stores (or other stuff) using React's context mechanism to child components.
This is useful if you have things that you don't want to pass through multiple layers of components explicitly.
inject can be used to pick up those stores. It is a higher order component that takes a list of strings and makes those stores available to the wrapped component.
Example (based on the official context docs):
@inject("color")
@observer
class Button extends React.Component {
render() {
return <button style={{ background: this.props.color }}>{this.props.children}</button>
}
}
class Message extends React.Component {
render() {
return (
<div>
{this.props.text} <Button>Delete</Button>
</div>
)
}
}
class MessageList extends React.Component {
render() {
const children = this.props.messages.map(message => <Message text={message.text} />)
return (
<Provider color="red">
<div>{children}</div>
</Provider>
)
}
}
Notes:
- It is possible to read the stores provided by
Provider using React.useContext, by using the MobXProviderContext context that can be imported from mobx-react.
- If a component asks for a store and receives a store via a property with the same name, the property takes precedence. Use this to your advantage when testing!
- When using both
@inject and @observer, make sure to apply them in the correct order: observer should be the inner decorator, inject the outer. There might be additional decorators in between.
- The original component wrapped by
inject is available as the wrappedComponent property of the created higher order component.
"The set of provided stores has changed" error
Values provided through Provider should be final. Make sure that if you put things in context that might change over time, that they are @observable or provide some other means to listen to changes, like callbacks. However, if your stores will change over time, like an observable value of another store, MobX will throw an error.
This restriction exists mainly for legacy reasons. If you have a scenario where you need to modify the set of stores, please leave a comment about it in this issue https://github.com/mobxjs/mobx-react/issues/745. Or a preferred way is to use React Context directly which does not have this restriction.
Inject as function
The above example in ES5 would start like:
var Button = inject("color")(
observer(
class Button extends Component {
/* ... etc ... */
}
)
)
A functional stateless component would look like:
var Button = inject("color")(
observer(({ color }) => {
/* ... etc ... */
})
)
Customizing inject