'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.
- observable states are being called and used.
- observable states are been passed into props
- 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 ?
Solution 1:[1]
Basically this https://mobx.js.org/refguide/observer-component.html#when-to-apply-observer and https://mobx.js.org/best/pitfalls.html#use-observer-on-all-components-that-render-observable-s
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.
Solution 2:[2]
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
Solution 3:[3]
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,
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Danila |
Solution 2 | lotem hiki |
Solution 3 | FreeDevM |