dante
dante

Reputation: 1111

When should I use observer in mobx-react?

I'm doing on migration all of my class component to functional component using mobx-react

I wonder all of my components should wrapped by observer or not.

I guess there might be three scenarios.

  1. observable states are being called and used.
  2. observable states are been passed into props
  3. purely stateless component.

let's say all of three components above are functional component.

Should I wrap all the components above with observer of mobx-react?

cf) Is there any articles or benchmarking compares to @observer decorators of mobx ?

Upvotes: 2

Views: 6075

Answers (3)

Danila
Danila

Reputation: 18476

Basically this https://mobx.js.org/react-integration.html#always-read-observables-inside-observer-components

You usually wrap everything in observer, exception might be components which only render primitives or something like this, but it is tedious to track it so usually you just wrap all of them.

Upvotes: 4

FreeDevM
FreeDevM

Reputation: 181

If I understood the question correctly, the right answer is on the documentation Mobx site: You might be wondering, when do I apply observer?

You might be wondering, when do I apply observer? The rule of thumb is: apply observer to all components that read observable data. observer only enhances the component you are decorating, not the components called by it. So usually all your components should be wrapped by observer. Don't worry, this is not inefficient. On the contrary, more observer components make rendering more efficient as updates become more fine-grained.

p.s.: there are broken links in first reply,

Upvotes: 0

lotem hiki
lotem hiki

Reputation: 1

Mobx's guideline is to put it on any component that reads observable data: https://mobx.js.org/react-integration.html#always-read-observables-inside-observer-components

Upvotes: 0

Related Questions