3

Question: Is it an anti pattern to both have mobx and react, then utilise both reacts component states, and the @observer @observable from mobx?

Since from what i can understand, mobx tries to replace the react states, or at least does something that is very similar.

1
  • 1
    The question is why would you do so? In one of my projects, I managed most the entire app's state using MobX, but I had a modal dialog component which needed to be a stateful component, so I managed that specific component's state with setState() because it seemed unnecessary to use MobX there ( but I might as well could have )
    – Dor Weid
    Commented Nov 30, 2016 at 16:39

2 Answers 2

2

I wouldn't call it an anti-pattern, but it defeats one of my favorite aspects of MobX. When using MobX, you are only ever dealing with props. I like this, because I never have to worry about whether a property lives in props or state. Since I started using MobX, I have never had a situation where I needed "state" local to a component. I find it best to keep all app state in stores, pass that state into top level components as props...

However, if you needed to have a "stateful" component using MobX, you could do something like this.

import React, { Component } from 'react';
import { action, observable }  from 'mobx';
import { observer } from 'mobx-react';

@observer
export default class User extends Component {
    @observable user = {
        firstName: 'john',
        lastName: 'lennon',
        status: 'alive'
    };

    @action updateUserStatus(newStatus) {
        this.user.status = newStatus
    }

    render() {
        const { firstName, lastName, status } = this;

        return (
            <p>{firstName} {lastName} - {status}</p>
        );
    }
}
0

Using React components' internal state and MobX store together is not an anti-pattern in the broad sense. But consider the following points:

  • Mixing component's internal state and a global state for the same purpose is not good. You will end up with conflicting states, you lose predictability and it becomes difficult to maintain.
  • I believe anything that can be called as a business logic should go in the global state.

  • states that can be isolated to a single component can reside inside the component itself as far as it is not part of the business logic and our components should just observe them.

  • Make your child components an @observer. Why? read it here (replace @connect with @observer)
  • MobX derivations are great substitutes for memoized custom getter/selector functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.