mobx-react 0,1,1 travis-ci npm webpack

React bindings for MobX

mobx-react

Build Status Join the chat at https://gitter.im/mobxjs/mobx #mobservable channel on reactiflux discord

Package with react component wrapper for combining React with mobx. Exports the observer decorator and some development utilities. For documentation, see the mobx project. This package supports both React and React-Native.

Installation

npm install mobx-react --save

Or CDN: https://unpkg.com/mobx-react (namespace: mobxReact)

import {observer} from 'mobx-react';
// - or -
import {observer} from 'mobx-react/native';
// - or, for custom renderers without DOM: -
import {observer} from 'mobx-react/custom';

This package provides the bindings for MobX and React. See the official documentation for how to get started.

Boilerplate projects that use mobx-react

API documentation

observer(componentClass)

Function (and decorator) that converts a React component definition, React component class or stand-alone render function into a reactive component. See the mobx documentation for more details.

import {observer} from "mobx-react";

// ---- ES5 syntax ----

const TodoView = observer(React.createClass({
    displayName: "TodoView",
    render() {
        return <div>{this.props.todo.title}</div>
    }
}));

// ---- ES6 syntax ----

const TodoView  = observer(class TodoView extends React.Component {
    render() {
        return <div>{this.props.todo.title}</div>
    }
})

// ---- ESNext syntax with decorators ----

@observer class TodoView extends React.Component {
    render() {
        return <div>{this.props.todo.title}</div>
    }
}

// ---- or just use a stateless component function: ----

const TodoView = observer(({todo}) => <div>{todo.title}</div>)

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

About shouldComponentUpdate

It is possible to set a custom shouldComponentUpdate, but in general this should be avoid as MobX will by default provide a highly optimized shouldComponentUpdate implementation, based on PureRenderMixin. If a custom shouldComponentUpdate is provided, it is consulted when the props changes (because the parent passes new props) or the state changes (as a result of calling setState), but if an observable used by the rendering is changed, the component will be re-rendered and shouldComponent is not consulted.

componentWillReact (lifecycle hook)

React components usually render on a fresh stack, so that makes it often hard to figure out what caused a component to re-render. When using mobx-react you can define a new life cycle hook, componentWillReact (pun intended) that will be triggered when a component will be scheduled to re-render because data it observes has changed. This makes it easy to trace renders back to the action that caused the rendering.

import {observer} from "mobx-react";

@observer class TodoView extends React.Component {
    componentWillReact() {
        console.log("I will re-render, since the todo has changed!");
    }

    render() {
        return <div>{this.props.todo.title}</div>
    }
}
  • componentWillReact doesn't take arguments
  • componentWillReact won't fire before the initial render (use componentWillMount instead)
  • componentWillReact won't fire when receiving new props or after setState calls (use componentWillUpdate instead)

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

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:

  • 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!
  • Values provided through Provider should be final, to avoid issues like mentioned in React #2517 and React #3973, where optimizations might stop the propagation of new context. Instead, 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.
  • 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 created the higher order component.

Inject as function

The above example in ES5 would start like:

var Button = inject("color")(observer(React.createClass({
    /* ... etc ... */
})))

A functional stateless component would look like:

var Button = inject("color")(observer(({ color }) => {
    /* ... etc ... */
}))

Omitting inject

If you are using inject with just store names, and there are no other (third party) decorators on the same component, you can pass the store names directly to observer as well, which will create an inject under the hood. (Mind the array notation!)

var Button = observer(["color"], ({ color }) => {
    /* ... etc ... */
}))

@observer(["session", "theme"])
class MyComponent extends React.Component {
  // etc
}

Strongly typing inject

inject also accepts a function ((allStores, nextProps, nextContext) => additionalProps) that can be used to pick all the desired stores from the available stores like this. The additionalProps will be merged into the original nextProps before being provided to the next component.

import {IUserStore} from "myStore"

@inject((allStores) => ({
    userStore: allStores.userStore as IUserStore
}))
class MyComponent extends React.Component<{ userStore?: IUserStore; otherProp: number }, {}> {
    /* etc */
}

Make sure to mark userStore as optional property. It should not (necessarily) be passed in by parent components after all!

Testing store injection

It is allowed to pass any declared stored in directly as property as well. This makes it easy to set up individual component tests without a provider.

So if you have in your app something like:

<Provider profile ={profile}>
    <Person age={'30'} />
</Provider>

In your test you can easily test the Person component by passing the necessary store as prop directly:

const profile = new Profile()
const mountedComponent = mount(
   <Person age={'30'} profile={profile} />
)

FAQ

Should I use observer for each component?

You should use observer on every component that displays observable data. Even the small ones. observer allows components to render independently from their parent and in general this means that the more you use observer, the better the performance become. The overhead of observer itself is neglectable. See also Do child components need @observer?

I see React warnings about forceUpdate / setState from React

The following warning will appear if you trigger a re-rendering between instantiating and rendering a component:

Warning: forceUpdate(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.`

-- or --

Warning: setState(...): Cannot update during an existing state transition (such as within `render` or another component's constructor). Render methods should be a pure function of props and state; constructor side-effects are an anti-pattern, but can be moved to `componentWillMount`.

Usually this means that (another) component is trying to modify observables used by this components in their constructor or getInitialState methods. This violates the React Lifecycle, componentWillMount should be used instead if state needs to be modified before mounting.

Internal DevTools Api

trackComponents()

Enables the tracking from components. Each rendered reactive component will be added to the componentByNodeRegistery and its renderings will be reported through the renderReporter event emitter.

renderReporter

Event emitter that reports render timings and component destructions. Only available after invoking trackComponents(). New listeners can be added through renderReporter.on(function(data) { /* */ }).

Data will have one of the following formats:

{
    event: 'render',
    renderTime: /* time spend in the .render function of a component, in ms. */,
    totalTime: /* time between starting a .render and flushing the changes to the DOM, in ms. */,
    component: /* component instance */,
    node: /* DOM node */
}
{
    event: 'destroy',
    component: /* component instance */,
    node: /* DOM Node */
}

componentByNodeRegistery

WeakMap. Its get function returns the associated reactive component of the given node. The node needs to be precisely the root node of the component. This map is only available after invoking trackComponents.

Related Repositories

mobx-react-devtools

mobx-react-devtools

Tools to perform runtime analyses of React applications powered by MobX and Reac ...

react-mobx-react-router4-boilerplate

react-mobx-react-router4-boilerplate

React, React-Router 4, MobX and Webpack 2-boilerplate with async routes. ...

mobx-react-boilerplate

mobx-react-boilerplate

Small project to quickly start with React, MobX, JSX, ES6, Babel ...

mobx-react-todomvc

mobx-react-todomvc

TodoMVC reference implementation on top of react-mobx-boilerplate ...

mobx-react-form

mobx-react-form

Automagically manage React forms state and automatic validation with MobX ...


Top Contributors

mweststrate andykog capaj benjamingr danieldunderfelt bartonhammond jtraub birkir andreigabreanu jesstelford bebraw mattruby rwieruch skvale Mosho1 bkniffler pvasek

Dependencies

package version
hoist-non-react-statics ^1.2.0
dev babel-core ^6.24.1
babel-plugin-external-helpers ^6.22.0
babel-plugin-transform-class-properties ^6.24.1
babel-plugin-transform-decorators-legacy ^1.3.4
babel-preset-es2015 ^6.24.1
babel-preset-es2015-rollup ^3.0.0
babel-preset-react ^6.24.1
babelify ^7.3.0
browserify ^14.3.0
enzyme ^2.8.0
lodash ^4.17.4
mobx ^3.1.9
nscript ^0.1.10
react ^15.5.3
react-addons-test-utils ^15.5.1
react-dom ^15.5.3
react-test-renderer ^15.5.4
rollup ^0.41.6
rollup-plugin-alias ^1.3.0
rollup-plugin-babel ^2.7.1
rollup-plugin-commonjs ^8.0.2
rollup-plugin-filesize ^1.2.1
rollup-plugin-node-resolve ^3.0.0
rollup-plugin-replace ^1.1.1
rollup-plugin-uglify ^1.0.1
tap-spec ^4.1.1
tape ^4.2.2
tape-run 2.1.0
typescript ~2.3.0
peer mobx ^2.6.3 || ^3.0.0
react ^0.13.0 || ^0.14.0 || ^15.0.0 || ^16.0.0-0

Releases

-   3.5.8 zip tar
-   3.5.7 zip tar
-   3.5.6 zip tar
-   3.5.5 zip tar
-   3.5.4 zip tar
-   3.5.3 zip tar
-   3.5.2 zip tar
-   3.5.1 zip tar
-   3.5.0 zip tar
-   3.4.0 zip tar
-   3.4.0-beta.1 zip tar
-   3.3.1 zip tar
-   3.3.0 zip tar
-   3.2.0 zip tar
-   3.1.0 zip tar
-   3.0.5 zip tar
-   3.0.4 zip tar
-   3.0.3 zip tar
-   3.0.2 zip tar
-   3.0.1 zip tar
-   3.0.0 zip tar
-   2.1.5 zip tar
-   2.1.4 zip tar
-   2.1.3 zip tar
-   2.1.2 zip tar
-   2.1.1 zip tar
-   2.1.0 zip tar
-   2.0.1 zip tar
-   2.0.0 zip tar
-   1.0.3 zip tar