mobx-react 5.3.6 → 5.4.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,515 +1,517 @@
1
- # mobx-react
2
-
3
- [![Build Status](https://travis-ci.org/mobxjs/mobx-react.svg?branch=master)](https://travis-ci.org/mobxjs/mobx-react)
4
- [![Join the chat at https://gitter.im/mobxjs/mobx](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mobxjs/mobx?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
5
- [![CDNJS](https://img.shields.io/cdnjs/v/mobx-react.svg)](https://cdnjs.com/libraries/mobx-react)
6
-
7
- Package with React component wrapper for combining React with MobX.
8
- Exports the `observer` decorator and some development utilities.
9
- For documentation, see the [MobX](https://mobxjs.github.io/mobx) project.
10
- This package supports both React and React Native.
11
-
12
- ## Installation
13
-
14
- `npm install mobx-react --save`
15
-
16
- Or CDN: https://unpkg.com/mobx-react (namespace: `mobxReact`)
17
-
18
- ```javascript
19
- import { observer } from "mobx-react"
20
- // - or, for custom renderers without DOM: -
21
- import { observer } from "mobx-react/custom"
22
- ```
23
-
24
- This package provides the bindings for MobX and React.
25
- See the [official documentation](http://mobxjs.github.io/mobx/intro/overview.html) for how to get started.
26
-
27
- ## Boilerplate projects that use mobx-react
28
-
29
- * Minimal MobX, React, ES6, JSX, Hot reloading: [MobX-React-Boilerplate](https://github.com/mobxjs/mobx-react-boilerplate)
30
- * TodoMVC MobX, React, ES6, JSX, Hot reloading: [MobX-React-TodoMVC](https://github.com/mobxjs/mobx-react-todomvc)
31
- * Minimal MobX, React, Typescript, TSX: [MobX-React-Typescript-Boilerplate](https://github.com/mobxjs/mobx-react-typescript-boilerplate)
32
- * Minimal MobX, React, ES6(babel), JSPM with hot reloading modules:
33
- [jspm-react](https://github.com/capaj/jspm-react)
34
- * React Native Counter: [Mobx-React-Native-Counter](https://github.com/bartonhammond/mobx-react-native-counter)
35
-
36
- ## API documentation
37
-
38
- ### observer(componentClass)
39
-
40
- Function (and decorator) that converts a React component definition, React component class or stand-alone render function into a reactive component, which tracks which observables are used by `render` and automatically re-renders the component when one of these values changes.
41
-
42
- Apart from observables passed/injected in or defined inside an `observer` component, `this.props` and `this.state` are also observables themselves, so the component will react to all changes in props and state that are used by `render`.
43
-
44
- See the [MobX](https://mobxjs.github.io/mobx/refguide/observer-component.html) documentation for more details.
45
-
46
- ```javascript
47
- import { observer } from "mobx-react"
48
-
49
- // ---- ES5 syntax ----
50
-
51
- const TodoView = observer(
52
- React.createClass({
53
- displayName: "TodoView",
54
- render() {
55
- return <div>{this.props.todo.title}</div>
56
- }
57
- })
58
- )
59
-
60
- // ---- ES6 syntax ----
61
-
62
- const TodoView = observer(
63
- class TodoView extends React.Component {
64
- render() {
65
- return <div>{this.props.todo.title}</div>
66
- }
67
- }
68
- )
69
-
70
- // ---- ESNext syntax with decorators ----
71
-
72
- @observer
73
- class TodoView extends React.Component {
74
- render() {
75
- return <div>{this.props.todo.title}</div>
76
- }
77
- }
78
-
79
- // ---- or just use a stateless component function: ----
80
-
81
- const TodoView = observer(({ todo }) => <div>{todo.title}</div>)
82
- ```
83
-
84
- ### `Observer`
85
-
86
- `Observer` is a React component, which applies `observer` to an anonymous region in your component.
87
- It takes as children a single, argumentless function which should return exactly one React component.
88
- The rendering in the function will be tracked and automatically re-rendered when needed.
89
- This can come in handy when needing to pass render function to external components (for example the React Native listview), or if you
90
- dislike the `observer` decorator / function.
91
-
92
- ```javascript
93
- class App extends React.Component {
94
- render() {
95
- return (
96
- <div>
97
- {this.props.person.name}
98
- <Observer>{() => <div>{this.props.person.name}</div>}</Observer>
99
- </div>
100
- )
101
- }
102
- }
103
-
104
- const person = observable({ name: "John" })
105
-
106
- React.render(<App person={person} />, document.body)
107
- person.name = "Mike" // will cause the Observer region to re-render
108
- ```
109
-
110
- 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.
111
- Example
112
-
113
- ```javascript
114
- class App extends React.Component {
115
- render() {
116
- return (
117
- <div>
118
- {this.props.person.name}
119
- <Observer render={() => <div>{this.props.person.name}</div>} />
120
- </div>
121
- )
122
- }
123
- }
124
-
125
- const person = observable({ name: "John" })
126
-
127
- React.render(<App person={person} />, document.body)
128
- person.name = "Mike" // will cause the Observer region to re-render
129
- ```
130
-
131
- ### Global error handler with `onError`
132
-
133
- If a component throws an error, this logs to the console but does not 'crash' the app, so it might go unnoticed.
134
- For this reason it is possible to attach a global error handler using `onError` to intercept any error thrown in the render of an `observer` component.
135
- This can be used to hook up any client side error collection system.
136
-
137
- ```javascript
138
- import { onError } from "mobx-react"
139
-
140
- onError(error => {
141
- console.log(error)
142
- })
143
- ```
144
-
145
- ### Server Side Rendering with `useStaticRendering`
146
-
147
- When using server side rendering, normal lifecycle hooks of React components are not fired, as the components are rendered only once.
148
- Since components are never unmounted, `observer` components would in this case leak memory when being rendered server side.
149
- To avoid leaking memory, call `useStaticRendering(true)` when using server side rendering.
150
-
151
- ```javascript
152
- import { useStaticRendering } from "mobx-react"
153
-
154
- useStaticRendering(true);
155
- ```
156
-
157
- This makes sure the component won't try to react to any future data changes.
158
-
159
- ### Which components should be marked with `observer`?
160
-
161
- The simple rule of thumb is: _all components that render observable data_.
162
- 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.
163
-
164
- ### Enabling decorators (optional)
165
-
166
- Decorators are currently a stage-2 ESNext feature. How to enable them is documented [here](https://github.com/mobxjs/mobx#enabling-decorators-optional).
167
-
168
- ### Should I still use smart and dumb components?
169
-
170
- See this [thread](https://www.reddit.com/r/reactjs/comments/4vnxg5/free_eggheadio_course_learn_mobx_react_in_30/d61oh0l).
171
- TL;DR: the conceptual distinction makes a lot of sense when using MobX as well, but use `observer` on all components.
172
-
173
- ### About `shouldComponentUpdate`
174
-
175
- When using `@observer` on a component, don't implement `shouldComponentUpdate`, as it will override the default implementation that MobX provides.
176
- When using mobx-react, you should in general not need to write an `sCU` (in our entire Mendix code base we have none). If you really need to implement `sCU`, split the component into two, a reactive and non-reactive (with the `sCU`) part, or use `<Observer>` sections instead of `observer` on the entire component.
177
-
178
- Similarly, `PureComponent` should not be combined with `observer`. As pure components are supposed to be dumb and never update themselves automatically, but only by getting passed in new props from the parent. `observer` is the opposite, it makes components smart and dependency aware, allowing them to update without the parents even needing to be aware of the change.
179
-
180
- ### `componentWillReact` (lifecycle hook)
181
-
182
- React components usually render on a fresh stack, so that makes it often hard to figure out what _caused_ a component to re-render.
183
- When using `mobx-react` you can define a new life cycle hook, `componentWillReact` (pun intended) that will be triggered when a component is scheduled to be re-rendered because
184
- data it observes has changed. This makes it easy to trace renders back to the action that caused the rendering.
185
-
186
- ```javascript
187
- import { observer } from "mobx-react"
188
-
189
- @observer
190
- class TodoView extends React.Component {
191
- componentWillReact() {
192
- console.log("I will re-render, since the todo has changed!")
193
- }
194
-
195
- render() {
196
- return <div>{this.props.todo.title}</div>
197
- }
198
- }
199
- ```
200
-
201
- * `componentWillReact` doesn't take arguments
202
- * `componentWillReact` won't fire before the initial render (use use `componentDidMount` or `constructor` instead)
203
-
204
- ### `PropTypes`
205
-
206
- MobX-react provides the following additional `PropTypes` which can be used to validate against MobX structures:
207
-
208
- * `observableArray`
209
- * `observableArrayOf(React.PropTypes.number)`
210
- * `observableMap`
211
- * `observableObject`
212
- * `arrayOrObservableArray`
213
- * `arrayOrObservableArrayOf(React.PropTypes.number)`
214
- * `objectOrObservableObject`
215
-
216
- Use `import { PropTypes } from "mobx-react"` to import them, then use for example `PropTypes.observableArray`
217
-
218
- ### `Provider` and `inject`
219
-
220
- `Provider` is a component that can pass stores (or other stuff) using React's context mechanism to child components.
221
- This is useful if you have things that you don't want to pass through multiple layers of components explicitly.
222
-
223
- `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.
224
-
225
- Example (based on the official [context docs](https://facebook.github.io/react/docs/context.html#passing-info-automatically-through-a-tree)):
226
-
227
- ```javascript
228
- @inject("color")
229
- @observer
230
- class Button extends React.Component {
231
- render() {
232
- return <button style={{ background: this.props.color }}>{this.props.children}</button>
233
- }
234
- }
235
-
236
- class Message extends React.Component {
237
- render() {
238
- return (
239
- <div>
240
- {this.props.text} <Button>Delete</Button>
241
- </div>
242
- )
243
- }
244
- }
245
-
246
- class MessageList extends React.Component {
247
- render() {
248
- const children = this.props.messages.map(message => <Message text={message.text} />)
249
- return (
250
- <Provider color="red">
251
- <div>{children}</div>
252
- </Provider>
253
- )
254
- }
255
- }
256
- ```
257
-
258
- Notes:
259
-
260
- * 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!
261
- * If updates to an observable store are not triggering `render()`, make sure you are using Class methods for React lifecycle hooks such as `componentWillMount() {}`, using `componentWillMount = () => {}` will create a property on the instance and cause conflicts with mobx-react.
262
- * Values provided through `Provider` should be final, to avoid issues like mentioned in [React #2517](https://github.com/facebook/react/issues/2517) and [React #3973](https://github.com/facebook/react/pull/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. However, if your stores will change over time, like an observable value of another store, MobX will warn you. To suppress that warning explicitly, you can use `suppressChangedStoreWarning={true}` as a prop at your own risk.
263
- * 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.
264
- * The original component wrapped by `inject` is available as the `wrappedComponent` property of the created higher order component.
265
- * For mounted component instances, the wrapped component instance is available through the `wrappedInstance` property (except for stateless components).
266
-
267
- #### Inject as function
268
-
269
- The above example in ES5 would start like:
270
-
271
- ```javascript
272
- var Button = inject("color")(
273
- observer(
274
- React.createClass({
275
- /* ... etc ... */
276
- })
277
- )
278
- )
279
- ```
280
-
281
- A functional stateless component would look like:
282
-
283
- ```javascript
284
- var Button = inject("color")(
285
- observer(({ color }) => {
286
- /* ... etc ... */
287
- })
288
- )
289
- ```
290
-
291
- #### Customizing inject
292
-
293
- Instead of passing a list of store names, it is also possible to create a custom mapper function and pass it to inject.
294
- The mapper function receives all stores as argument, the properties with which the components are invoked and the context, and should produce a new set of properties,
295
- that are mapped into the original:
296
-
297
- `mapperFunction: (allStores, props, context) => additionalProps`
298
-
299
- Since version 4.0 the `mapperFunction` itself is tracked as well, so it is possible to do things like:
300
-
301
- ```javascript
302
- const NameDisplayer = ({ name }) => <h1>{name}</h1>
303
-
304
- const UserNameDisplayer = inject(stores => ({
305
- name: stores.userStore.name
306
- }))(NameDisplayer)
307
-
308
- const user = mobx.observable({
309
- name: "Noa"
310
- })
311
-
312
- const App = () => (
313
- <Provider userStore={user}>
314
- <UserNameDisplayer />
315
- </Provider>
316
- )
317
-
318
- ReactDOM.render(<App />, document.body)
319
- ```
320
-
321
- _N.B. note that in this *specific* case neither `NameDisplayer` nor `UserNameDisplayer` needs to be decorated with `observer`, since the observable dereferencing is done in the mapper function_
322
-
323
- #### Using `propTypes` and `defaultProps` and other static properties in combination with `inject`
324
-
325
- Inject wraps a new component around the component you pass into it.
326
- This means that assigning a static property to the resulting component, will be applied to the HoC, and not to the original component.
327
- So if you take the following example:
328
-
329
- ```javascript
330
- const UserName = inject("userStore")(({ userStore, bold }) => someRendering())
331
-
332
- UserName.propTypes = {
333
- bold: PropTypes.boolean.isRequired,
334
- userStore: PropTypes.object.isRequired // will always fail
335
- }
336
- ```
337
-
338
- The above propTypes are incorrect, `bold` needs to be provided by the caller of the `UserName` component and is checked by React.
339
- However, `userStore` does not need to be required! Although it is required for the original stateless function component, it is not
340
- required for the resulting inject component. After all, the whole point of that component is to provide that `userStore` itself.
341
-
342
- So if you want to make assertions on the data that is being injected (either stores or data resulting from a mapper function), the propTypes
343
- should be defined on the _wrapped_ component. Which is available through the static property `wrappedComponent` on the inject component:
344
-
345
- ```javascript
346
- const UserName = inject("userStore")(({ userStore, bold }) => someRendering())
347
-
348
- UserName.propTypes = {
349
- bold: PropTypes.boolean.isRequired // could be defined either here ...
350
- }
351
-
352
- UserName.wrappedComponent.propTypes = {
353
- // ... or here
354
- userStore: PropTypes.object.isRequired // correct
355
- }
356
- ```
357
-
358
- The same principle applies to `defaultProps` and other static React properties.
359
- Note that it is not allowed to redefine `contextTypes` on `inject` components (but is possible to define it on `wrappedComponent`)
360
-
361
- Finally, mobx-react will automatically move non React related static properties from wrappedComponent to the inject component so that all static fields are
362
- actually available to the outside world without needing `.wrappedComponent`.
363
-
364
- #### Strongly typing inject
365
-
366
- ##### With TypeScript
367
-
368
- `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.
369
- The `additionalProps` will be merged into the original `nextProps` before being provided to the next component.
370
-
371
- ```typescript
372
- import { IUserStore } from "myStore"
373
-
374
- @inject(allStores => ({
375
- userStore: allStores.userStore as IUserStore
376
- }))
377
- class MyComponent extends React.Component<{ userStore?: IUserStore; otherProp: number }, {}> {
378
- /* etc */
379
- }
380
- ```
381
-
382
- Make sure to mark `userStore` as an optional property. It should not (necessarily) be passed in by parent components at all!
383
-
384
- Note: If you have strict null checking enabled, you could muffle the nullable type by using the `!` operator:
385
-
386
- ```
387
- public render() {
388
- const {a, b} = this.store!
389
- // ...
390
- }
391
- ```
392
-
393
- ##### With Flow
394
-
395
- Currently, there is a community-discussion around the best way to use `inject` with Flow. Join the discussion at [this gist](https://gist.github.com/vonovak/29c972c6aa9efbb7d63a6853d021fba9).
396
-
397
- #### Testing store injection
398
-
399
- It is allowed to pass any declared store in directly as a property as well. This makes it easy to set up individual component tests without a provider.
400
-
401
- So if you have in your app something like:
402
-
403
- ```javascript
404
- <Provider profile={profile}>
405
- <Person age={"30"} />
406
- </Provider>
407
- ```
408
-
409
- In your test you can easily test the `Person` component by passing the necessary store as prop directly:
410
-
411
- ```
412
- const profile = new Profile()
413
- const mountedComponent = mount(
414
- <Person age={'30'} profile={profile} />
415
- )
416
- ```
417
-
418
- Bear in mind that using shallow rendering won't provide any useful results when testing injected components; only the injector will be rendered.
419
- To test with shallow rendering, instantiate the `wrappedComponent` instead: `shallow(<Person.wrappedComponent />)`
420
-
421
- ### disposeOnUnmount(componentInstance, propertyKey | function | function[])
422
-
423
- Function (and decorator) that makes sure a function (usually a disposer such as the ones returned by `reaction`, `autorun`, etc.) is automatically executed as part of the componentWillUnmount lifecycle event.
424
-
425
- ```javascript
426
- import { disposeOnUnmount } from "mobx-react"
427
-
428
- class SomeComponent extends React.Component {
429
- // decorator version
430
- @disposeOnUnmount
431
- someReactionDisposer = reaction(...)
432
-
433
- // function version over properties
434
- someReactionDisposer = disposeOnUnmount(this, reaction(...))
435
-
436
- // function version inside methods
437
- componentDidMount() {
438
- // single function
439
- disposeOnUnmount(this, reaction(...))
440
-
441
- // or function array
442
- disposeOnUmount(this, [
443
- reaction(...),
444
- reaction(...)
445
- ])
446
- }
447
- }
448
- ```
449
-
450
- ## FAQ
451
-
452
- **Should I use `observer` for each component?**
453
-
454
- You should use `observer` on every component that displays observable data.
455
- Even the small ones. `observer` allows components to render independently from their parent and in general this means that
456
- the more you use `observer`, the better the performance become.
457
- The overhead of `observer` itself is negligible.
458
- See also [Do child components need `@observer`?](https://github.com/mobxjs/mobx/issues/101)
459
-
460
- **I see React warnings about `forceUpdate` / `setState` from React**
461
-
462
- The following warning will appear if you trigger a re-rendering between instantiating and rendering a component:
463
-
464
- ```
465
- Warning: forceUpdate(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.`
466
- ```
467
-
468
- -- or --
469
-
470
- ```
471
- 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`.
472
- ```
473
-
474
- Usually this means that (another) component is trying to modify observables used by this components in their `constructor` or `getInitialState` methods.
475
- This violates the React Lifecycle, `componentWillMount` should be used instead if state needs to be modified before mounting.
476
-
477
- ## Internal DevTools Api
478
-
479
- ### trackComponents()
480
-
481
- 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.
482
-
483
- ### renderReporter
484
-
485
- Event emitter that reports render timings and component destructions. Only available after invoking `trackComponents()`.
486
- New listeners can be added through `renderReporter.on(function(data) { /* */ })`.
487
-
488
- Data will have one of the following formats:
489
-
490
- ```javascript
491
- {
492
- event: 'render',
493
- renderTime: /* time spend in the .render function of a component, in ms. */,
494
- totalTime: /* time between starting a .render and flushing the changes to the DOM, in ms. */,
495
- component: /* component instance */,
496
- node: /* DOM node */
497
- }
498
- ```
499
-
500
- ```javascript
501
- {
502
- event: 'destroy',
503
- component: /* component instance */,
504
- node: /* DOM Node */
505
- }
506
- ```
507
-
508
- ### componentByNodeRegistery
509
-
510
- 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.
511
- This map is only available after invoking `trackComponents`.
512
-
513
- ### Debugging reactions with trace
514
-
515
- Using Mobx.trace() inside a React render function will print out the observable that triggered the change. See [the mobx trace docs](https://mobx.js.org/best/trace.html) for more information.
1
+ # mobx-react
2
+
3
+ [![Build Status](https://travis-ci.org/mobxjs/mobx-react.svg?branch=master)](https://travis-ci.org/mobxjs/mobx-react)
4
+ [![Join the chat at https://gitter.im/mobxjs/mobx](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/mobxjs/mobx?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
5
+ [![CDNJS](https://img.shields.io/cdnjs/v/mobx-react.svg)](https://cdnjs.com/libraries/mobx-react)
6
+
7
+ Package with React component wrapper for combining React with MobX.
8
+ Exports the `observer` decorator and some development utilities.
9
+ For documentation, see the [MobX](https://mobxjs.github.io/mobx) project.
10
+ This package supports both React and React Native.
11
+
12
+ ## Installation
13
+
14
+ `npm install mobx-react --save`
15
+
16
+ Or CDN: https://unpkg.com/mobx-react (namespace: `mobxReact`)
17
+
18
+ ```javascript
19
+ import { observer } from "mobx-react"
20
+ // - or, for custom renderers without DOM: -
21
+ import { observer } from "mobx-react/custom"
22
+ ```
23
+
24
+ This package provides the bindings for MobX and React.
25
+ See the [official documentation](http://mobxjs.github.io/mobx/intro/overview.html) for how to get started.
26
+
27
+ If you are using [React hooks](https://reactjs.org/docs/hooks-intro.html) with latest React 16.7 and you like living on the bleeding edge then have a look at the new [mobx-react-lite](https://github.com/mobxjs/mobx-react-lite).
28
+
29
+ ## Boilerplate projects that use mobx-react
30
+
31
+ * Minimal MobX, React, ES6, JSX, Hot reloading: [MobX-React-Boilerplate](https://github.com/mobxjs/mobx-react-boilerplate)
32
+ * TodoMVC MobX, React, ES6, JSX, Hot reloading: [MobX-React-TodoMVC](https://github.com/mobxjs/mobx-react-todomvc)
33
+ * Minimal MobX, React, Typescript, TSX: [MobX-React-Typescript-Boilerplate](https://github.com/mobxjs/mobx-react-typescript-boilerplate)
34
+ * Minimal MobX, React, ES6(babel), JSPM with hot reloading modules:
35
+ [jspm-react](https://github.com/capaj/jspm-react)
36
+ * React Native Counter: [Mobx-React-Native-Counter](https://github.com/bartonhammond/mobx-react-native-counter)
37
+
38
+ ## API documentation
39
+
40
+ ### observer(componentClass)
41
+
42
+ Function (and decorator) that converts a React component definition, React component class or stand-alone render function into a reactive component, which tracks which observables are used by `render` and automatically re-renders the component when one of these values changes.
43
+
44
+ Apart from observables passed/injected in or defined inside an `observer` component, `this.props` and `this.state` are also observables themselves, so the component will react to all changes in props and state that are used by `render`.
45
+
46
+ See the [MobX](https://mobxjs.github.io/mobx/refguide/observer-component.html) documentation for more details.
47
+
48
+ ```javascript
49
+ import { observer } from "mobx-react"
50
+
51
+ // ---- ES5 syntax ----
52
+
53
+ const TodoView = observer(
54
+ React.createClass({
55
+ displayName: "TodoView",
56
+ render() {
57
+ return <div>{this.props.todo.title}</div>
58
+ }
59
+ })
60
+ )
61
+
62
+ // ---- ES6 syntax ----
63
+
64
+ const TodoView = observer(
65
+ class TodoView extends React.Component {
66
+ render() {
67
+ return <div>{this.props.todo.title}</div>
68
+ }
69
+ }
70
+ )
71
+
72
+ // ---- ESNext syntax with decorators ----
73
+
74
+ @observer
75
+ class TodoView extends React.Component {
76
+ render() {
77
+ return <div>{this.props.todo.title}</div>
78
+ }
79
+ }
80
+
81
+ // ---- or just use a stateless component function: ----
82
+
83
+ const TodoView = observer(({ todo }) => <div>{todo.title}</div>)
84
+ ```
85
+
86
+ ### `Observer`
87
+
88
+ `Observer` is a React component, which applies `observer` to an anonymous region in your component.
89
+ It takes as children a single, argumentless function which should return exactly one React component.
90
+ The rendering in the function will be tracked and automatically re-rendered when needed.
91
+ This can come in handy when needing to pass render function to external components (for example the React Native listview), or if you
92
+ dislike the `observer` decorator / function.
93
+
94
+ ```javascript
95
+ class App extends React.Component {
96
+ render() {
97
+ return (
98
+ <div>
99
+ {this.props.person.name}
100
+ <Observer>{() => <div>{this.props.person.name}</div>}</Observer>
101
+ </div>
102
+ )
103
+ }
104
+ }
105
+
106
+ const person = observable({ name: "John" })
107
+
108
+ React.render(<App person={person} />, document.body)
109
+ person.name = "Mike" // will cause the Observer region to re-render
110
+ ```
111
+
112
+ 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.
113
+ Example
114
+
115
+ ```javascript
116
+ class App extends React.Component {
117
+ render() {
118
+ return (
119
+ <div>
120
+ {this.props.person.name}
121
+ <Observer render={() => <div>{this.props.person.name}</div>} />
122
+ </div>
123
+ )
124
+ }
125
+ }
126
+
127
+ const person = observable({ name: "John" })
128
+
129
+ React.render(<App person={person} />, document.body)
130
+ person.name = "Mike" // will cause the Observer region to re-render
131
+ ```
132
+
133
+ ### Global error handler with `onError`
134
+
135
+ If a component throws an error, this logs to the console but does not 'crash' the app, so it might go unnoticed.
136
+ For this reason it is possible to attach a global error handler using `onError` to intercept any error thrown in the render of an `observer` component.
137
+ This can be used to hook up any client side error collection system.
138
+
139
+ ```javascript
140
+ import { onError } from "mobx-react"
141
+
142
+ onError(error => {
143
+ console.log(error)
144
+ })
145
+ ```
146
+
147
+ ### Server Side Rendering with `useStaticRendering`
148
+
149
+ When using server side rendering, normal lifecycle hooks of React components are not fired, as the components are rendered only once.
150
+ Since components are never unmounted, `observer` components would in this case leak memory when being rendered server side.
151
+ To avoid leaking memory, call `useStaticRendering(true)` when using server side rendering.
152
+
153
+ ```javascript
154
+ import { useStaticRendering } from "mobx-react"
155
+
156
+ useStaticRendering(true);
157
+ ```
158
+
159
+ This makes sure the component won't try to react to any future data changes.
160
+
161
+ ### Which components should be marked with `observer`?
162
+
163
+ The simple rule of thumb is: _all components that render observable data_.
164
+ 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.
165
+
166
+ ### Enabling decorators (optional)
167
+
168
+ Decorators are currently a stage-2 ESNext feature. How to enable them is documented [here](https://github.com/mobxjs/mobx#enabling-decorators-optional).
169
+
170
+ ### Should I still use smart and dumb components?
171
+
172
+ See this [thread](https://www.reddit.com/r/reactjs/comments/4vnxg5/free_eggheadio_course_learn_mobx_react_in_30/d61oh0l).
173
+ TL;DR: the conceptual distinction makes a lot of sense when using MobX as well, but use `observer` on all components.
174
+
175
+ ### About `shouldComponentUpdate`
176
+
177
+ When using `@observer` on a component, don't implement `shouldComponentUpdate`, as it will override the default implementation that MobX provides.
178
+ When using mobx-react, you should in general not need to write an `sCU` (in our entire Mendix code base we have none). If you really need to implement `sCU`, split the component into two, a reactive and non-reactive (with the `sCU`) part, or use `<Observer>` sections instead of `observer` on the entire component.
179
+
180
+ Similarly, `PureComponent` should not be combined with `observer`. As pure components are supposed to be dumb and never update themselves automatically, but only by getting passed in new props from the parent. `observer` is the opposite, it makes components smart and dependency aware, allowing them to update without the parents even needing to be aware of the change.
181
+
182
+ ### `componentWillReact` (lifecycle hook)
183
+
184
+ React components usually render on a fresh stack, so that makes it often hard to figure out what _caused_ a component to re-render.
185
+ When using `mobx-react` you can define a new life cycle hook, `componentWillReact` (pun intended) that will be triggered when a component is scheduled to be re-rendered because
186
+ data it observes has changed. This makes it easy to trace renders back to the action that caused the rendering.
187
+
188
+ ```javascript
189
+ import { observer } from "mobx-react"
190
+
191
+ @observer
192
+ class TodoView extends React.Component {
193
+ componentWillReact() {
194
+ console.log("I will re-render, since the todo has changed!")
195
+ }
196
+
197
+ render() {
198
+ return <div>{this.props.todo.title}</div>
199
+ }
200
+ }
201
+ ```
202
+
203
+ * `componentWillReact` doesn't take arguments
204
+ * `componentWillReact` won't fire before the initial render (use use `componentDidMount` or `constructor` instead)
205
+
206
+ ### `PropTypes`
207
+
208
+ MobX-react provides the following additional `PropTypes` which can be used to validate against MobX structures:
209
+
210
+ * `observableArray`
211
+ * `observableArrayOf(React.PropTypes.number)`
212
+ * `observableMap`
213
+ * `observableObject`
214
+ * `arrayOrObservableArray`
215
+ * `arrayOrObservableArrayOf(React.PropTypes.number)`
216
+ * `objectOrObservableObject`
217
+
218
+ Use `import { PropTypes } from "mobx-react"` to import them, then use for example `PropTypes.observableArray`
219
+
220
+ ### `Provider` and `inject`
221
+
222
+ `Provider` is a component that can pass stores (or other stuff) using React's context mechanism to child components.
223
+ This is useful if you have things that you don't want to pass through multiple layers of components explicitly.
224
+
225
+ `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.
226
+
227
+ Example (based on the official [context docs](https://facebook.github.io/react/docs/context.html#passing-info-automatically-through-a-tree)):
228
+
229
+ ```javascript
230
+ @inject("color")
231
+ @observer
232
+ class Button extends React.Component {
233
+ render() {
234
+ return <button style={{ background: this.props.color }}>{this.props.children}</button>
235
+ }
236
+ }
237
+
238
+ class Message extends React.Component {
239
+ render() {
240
+ return (
241
+ <div>
242
+ {this.props.text} <Button>Delete</Button>
243
+ </div>
244
+ )
245
+ }
246
+ }
247
+
248
+ class MessageList extends React.Component {
249
+ render() {
250
+ const children = this.props.messages.map(message => <Message text={message.text} />)
251
+ return (
252
+ <Provider color="red">
253
+ <div>{children}</div>
254
+ </Provider>
255
+ )
256
+ }
257
+ }
258
+ ```
259
+
260
+ Notes:
261
+
262
+ * 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!
263
+ * If updates to an observable store are not triggering `render()`, make sure you are using Class methods for React lifecycle hooks such as `componentWillMount() {}`, using `componentWillMount = () => {}` will create a property on the instance and cause conflicts with mobx-react.
264
+ * Values provided through `Provider` should be final, to avoid issues like mentioned in [React #2517](https://github.com/facebook/react/issues/2517) and [React #3973](https://github.com/facebook/react/pull/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. However, if your stores will change over time, like an observable value of another store, MobX will warn you. To suppress that warning explicitly, you can use `suppressChangedStoreWarning={true}` as a prop at your own risk.
265
+ * 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.
266
+ * The original component wrapped by `inject` is available as the `wrappedComponent` property of the created higher order component.
267
+ * For mounted component instances, the wrapped component instance is available through the `wrappedInstance` property (except for stateless components).
268
+
269
+ #### Inject as function
270
+
271
+ The above example in ES5 would start like:
272
+
273
+ ```javascript
274
+ var Button = inject("color")(
275
+ observer(
276
+ React.createClass({
277
+ /* ... etc ... */
278
+ })
279
+ )
280
+ )
281
+ ```
282
+
283
+ A functional stateless component would look like:
284
+
285
+ ```javascript
286
+ var Button = inject("color")(
287
+ observer(({ color }) => {
288
+ /* ... etc ... */
289
+ })
290
+ )
291
+ ```
292
+
293
+ #### Customizing inject
294
+
295
+ Instead of passing a list of store names, it is also possible to create a custom mapper function and pass it to inject.
296
+ The mapper function receives all stores as argument, the properties with which the components are invoked and the context, and should produce a new set of properties,
297
+ that are mapped into the original:
298
+
299
+ `mapperFunction: (allStores, props, context) => additionalProps`
300
+
301
+ Since version 4.0 the `mapperFunction` itself is tracked as well, so it is possible to do things like:
302
+
303
+ ```javascript
304
+ const NameDisplayer = ({ name }) => <h1>{name}</h1>
305
+
306
+ const UserNameDisplayer = inject(stores => ({
307
+ name: stores.userStore.name
308
+ }))(NameDisplayer)
309
+
310
+ const user = mobx.observable({
311
+ name: "Noa"
312
+ })
313
+
314
+ const App = () => (
315
+ <Provider userStore={user}>
316
+ <UserNameDisplayer />
317
+ </Provider>
318
+ )
319
+
320
+ ReactDOM.render(<App />, document.body)
321
+ ```
322
+
323
+ _N.B. note that in this *specific* case neither `NameDisplayer` nor `UserNameDisplayer` needs to be decorated with `observer`, since the observable dereferencing is done in the mapper function_
324
+
325
+ #### Using `propTypes` and `defaultProps` and other static properties in combination with `inject`
326
+
327
+ Inject wraps a new component around the component you pass into it.
328
+ This means that assigning a static property to the resulting component, will be applied to the HoC, and not to the original component.
329
+ So if you take the following example:
330
+
331
+ ```javascript
332
+ const UserName = inject("userStore")(({ userStore, bold }) => someRendering())
333
+
334
+ UserName.propTypes = {
335
+ bold: PropTypes.boolean.isRequired,
336
+ userStore: PropTypes.object.isRequired // will always fail
337
+ }
338
+ ```
339
+
340
+ The above propTypes are incorrect, `bold` needs to be provided by the caller of the `UserName` component and is checked by React.
341
+ However, `userStore` does not need to be required! Although it is required for the original stateless function component, it is not
342
+ required for the resulting inject component. After all, the whole point of that component is to provide that `userStore` itself.
343
+
344
+ So if you want to make assertions on the data that is being injected (either stores or data resulting from a mapper function), the propTypes
345
+ should be defined on the _wrapped_ component. Which is available through the static property `wrappedComponent` on the inject component:
346
+
347
+ ```javascript
348
+ const UserName = inject("userStore")(({ userStore, bold }) => someRendering())
349
+
350
+ UserName.propTypes = {
351
+ bold: PropTypes.boolean.isRequired // could be defined either here ...
352
+ }
353
+
354
+ UserName.wrappedComponent.propTypes = {
355
+ // ... or here
356
+ userStore: PropTypes.object.isRequired // correct
357
+ }
358
+ ```
359
+
360
+ The same principle applies to `defaultProps` and other static React properties.
361
+ Note that it is not allowed to redefine `contextTypes` on `inject` components (but is possible to define it on `wrappedComponent`)
362
+
363
+ Finally, mobx-react will automatically move non React related static properties from wrappedComponent to the inject component so that all static fields are
364
+ actually available to the outside world without needing `.wrappedComponent`.
365
+
366
+ #### Strongly typing inject
367
+
368
+ ##### With TypeScript
369
+
370
+ `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.
371
+ The `additionalProps` will be merged into the original `nextProps` before being provided to the next component.
372
+
373
+ ```typescript
374
+ import { IUserStore } from "myStore"
375
+
376
+ @inject(allStores => ({
377
+ userStore: allStores.userStore as IUserStore
378
+ }))
379
+ class MyComponent extends React.Component<{ userStore?: IUserStore; otherProp: number }, {}> {
380
+ /* etc */
381
+ }
382
+ ```
383
+
384
+ Make sure to mark `userStore` as an optional property. It should not (necessarily) be passed in by parent components at all!
385
+
386
+ Note: If you have strict null checking enabled, you could muffle the nullable type by using the `!` operator:
387
+
388
+ ```
389
+ public render() {
390
+ const {a, b} = this.store!
391
+ // ...
392
+ }
393
+ ```
394
+
395
+ ##### With Flow
396
+
397
+ Currently, there is a community-discussion around the best way to use `inject` with Flow. Join the discussion at [this gist](https://gist.github.com/vonovak/29c972c6aa9efbb7d63a6853d021fba9).
398
+
399
+ #### Testing store injection
400
+
401
+ It is allowed to pass any declared store in directly as a property as well. This makes it easy to set up individual component tests without a provider.
402
+
403
+ So if you have in your app something like:
404
+
405
+ ```javascript
406
+ <Provider profile={profile}>
407
+ <Person age={"30"} />
408
+ </Provider>
409
+ ```
410
+
411
+ In your test you can easily test the `Person` component by passing the necessary store as prop directly:
412
+
413
+ ```
414
+ const profile = new Profile()
415
+ const mountedComponent = mount(
416
+ <Person age={'30'} profile={profile} />
417
+ )
418
+ ```
419
+
420
+ Bear in mind that using shallow rendering won't provide any useful results when testing injected components; only the injector will be rendered.
421
+ To test with shallow rendering, instantiate the `wrappedComponent` instead: `shallow(<Person.wrappedComponent />)`
422
+
423
+ ### disposeOnUnmount(componentInstance, propertyKey | function | function[])
424
+
425
+ Function (and decorator) that makes sure a function (usually a disposer such as the ones returned by `reaction`, `autorun`, etc.) is automatically executed as part of the componentWillUnmount lifecycle event.
426
+
427
+ ```javascript
428
+ import { disposeOnUnmount } from "mobx-react"
429
+
430
+ class SomeComponent extends React.Component {
431
+ // decorator version
432
+ @disposeOnUnmount
433
+ someReactionDisposer = reaction(...)
434
+
435
+ // function version over properties
436
+ someReactionDisposer = disposeOnUnmount(this, reaction(...))
437
+
438
+ // function version inside methods
439
+ componentDidMount() {
440
+ // single function
441
+ disposeOnUnmount(this, reaction(...))
442
+
443
+ // or function array
444
+ disposeOnUmount(this, [
445
+ reaction(...),
446
+ reaction(...)
447
+ ])
448
+ }
449
+ }
450
+ ```
451
+
452
+ ## FAQ
453
+
454
+ **Should I use `observer` for each component?**
455
+
456
+ You should use `observer` on every component that displays observable data.
457
+ Even the small ones. `observer` allows components to render independently from their parent and in general this means that
458
+ the more you use `observer`, the better the performance become.
459
+ The overhead of `observer` itself is negligible.
460
+ See also [Do child components need `@observer`?](https://github.com/mobxjs/mobx/issues/101)
461
+
462
+ **I see React warnings about `forceUpdate` / `setState` from React**
463
+
464
+ The following warning will appear if you trigger a re-rendering between instantiating and rendering a component:
465
+
466
+ ```
467
+ Warning: forceUpdate(...): Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.`
468
+ ```
469
+
470
+ -- or --
471
+
472
+ ```
473
+ 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`.
474
+ ```
475
+
476
+ Usually this means that (another) component is trying to modify observables used by this components in their `constructor` or `getInitialState` methods.
477
+ This violates the React Lifecycle, `componentWillMount` should be used instead if state needs to be modified before mounting.
478
+
479
+ ## Internal DevTools Api
480
+
481
+ ### trackComponents()
482
+
483
+ 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.
484
+
485
+ ### renderReporter
486
+
487
+ Event emitter that reports render timings and component destructions. Only available after invoking `trackComponents()`.
488
+ New listeners can be added through `renderReporter.on(function(data) { /* */ })`.
489
+
490
+ Data will have one of the following formats:
491
+
492
+ ```javascript
493
+ {
494
+ event: 'render',
495
+ renderTime: /* time spend in the .render function of a component, in ms. */,
496
+ totalTime: /* time between starting a .render and flushing the changes to the DOM, in ms. */,
497
+ component: /* component instance */,
498
+ node: /* DOM node */
499
+ }
500
+ ```
501
+
502
+ ```javascript
503
+ {
504
+ event: 'destroy',
505
+ component: /* component instance */,
506
+ node: /* DOM Node */
507
+ }
508
+ ```
509
+
510
+ ### componentByNodeRegistery
511
+
512
+ 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.
513
+ This map is only available after invoking `trackComponents`.
514
+
515
+ ### Debugging reactions with trace
516
+
517
+ Using Mobx.trace() inside a React render function will print out the observable that triggered the change. See [the mobx trace docs](https://mobx.js.org/best/trace.html) for more information.