-1

In most cases, I use observable with observer() in React components instead of React's state.

However, to use React's state with MobX is anti-pattern? For example, is this below anti-pattern?

@observer
class Counter extends React.Component {
  state = {
    count: 0
  };

  render() {
     return <button onClick={this._handleClick}>{count}</button>
  }

  _handleClick = () => {
    this.setState(prev => {count: prev.count + 1});
  };
}

I know it can be replaced with observable but I wonder if it is an anti-pattern.

Or, is it better to use observable than to use React's state in observed components? if so, why?

Yonggoo Noh
  • 1,811
  • 3
  • 22
  • 37

1 Answers1

0

The question is why do you have observer there since your component isn't using any observables. You won't gain anything here and you can drop it.

And generally, don't worry about anti-patterns much. As long as something works for you, it's totally fine. Don't let others force you into their opinionated patterns.

FredyC
  • 3,999
  • 4
  • 30
  • 38
  • In that code, if `observer` does not exist, I have to implement `shouldComponentUpdate` or use `React.PureComponent`. I'm wondering if I should use `observable` in observed component – Yonggoo Noh Sep 22 '20 at 07:37
  • Please read through https://mobx.js.org/react-integration.html? – FredyC Oct 03 '20 at 08:44