Search code examples
reactjsmobxmobx-reactmobx-state-treemobx-react-lite

MobX with React best practice with observer


I'm not really facing an issue, it's more like I'm wondering what is the best way I should use mobx with react. So here's my situation:

I'am fairly new to mobx but I've got years of experience using react (mostly with redux). My new project is using mobx-state-tree alongside with mobx-react-lite in order to connect my components with the function observer wrapping the component. I've set up a root store with multiples stores in it. I'm really enthusiastic about it for now but I would like some recommendations:

Should I use the containers logic which is pretty common with redux, which means I should only connect a "container" component who will handle the connection with my stores and spread it to its children ? Or should I connect directly with an observer as many components which needs to be provided with data from a store ?

Is the second option more optimized, technically speaking ? Is it still a good idea according to React philosophy ? What's YOUR opinion on this subject ?

Any answer would be really appreciated


Solution

  • Technically, you don't need container/presentation concept. You can use context, or localStore, or globalStore but it doesn't mean container/presentation not useful sometimes.

    Mobx patches shouldComponentUpdate lifecycle, and basically optimizes components rendering for you. mobx-react mentioned in their docs that the more components connected with observer, the better.

    It's very common pattern to see shouldComponentUpdate with a bulky checks to avoid unnecessary renders. This isn't needed with MobX at all.

    My opinion is that patterns change on monthly basis, so learning the general concepts can ease your transition from global store, local store, context, hooks and other api changes.

    React component patterns also change overtime.

    Use what you need and understand right now. If it won't matter in 5 years, don't spend more than 5 minutes to think about it. You can always do a fun refactor.

    Further reading:

    https://mobx.js.org/README.html

    https://mobx-react.js.org