Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Mobx is useful?

Tags:

reactjs

mobx

MobX web tutorial is really hard to get through. Can someone explain to me in plain English why MobX is useful when React already has a state management system?

like image 635
Chris Hansen Avatar asked Dec 07 '25 10:12

Chris Hansen


1 Answers

Mobx is a library for state management by applying functional reactive programming, it is very similar to observer pattern in OOP.

It is more convenienient, than regular react state management for components with a complex state.

  • With mobx you dont need to use useState many times. you can store state in an object, that looks just like a regular js object (but is actually a proxy object, that consists of getters and setters). Instead of calling setState several times, you can change mobx state object single time.
  • Mobx state object is not immutable, this is more convenient for nested state, as you don't need to create a shallow copy all the way to ensure immutability
  • You can decouple some logic from the component and thus simplify it (computeds, that are similar to useMemo).
  • Mobx is much more simpler, than redux, and more productive.

Here is a regular react example:

const Widgets = (props) => {
  const [widgets, setWidgets] = useState([])
  const [status, setStatus] = useState('loading') // loading, error, loaded

  const onLoaded = (widgets) => {
    setWidgets(widgets)
    setStatus('loaded')
  }

  
  const onClose = (widget) => {
    const index = widgets.findIndex(currWidget => widget === currWidget)
    const nextWidgets = [...widgets]
    nextWidgets[index] = { ...nextWidgets[index] }
    nextWidgets[index].status = 'animatingOut'
    setWidgets(nextWidgets)
  }

  
  const hasActiveWidgets = useMemo(() => widgets.some(widget => widget.isActive), [widgets])
  if(hasActiveToasts){
    // something
  }

  ...
}

Here is the same example with mobx:

class State {
  constructor(){
    makeAutoObservable(this) // use second parameter, to override, which properties to track and how
  }
  widgets: []
  status: 'loading'
  hasActiveWidgets: () => this.widgets.some(widget => widget.isActive)
}

const Widgets = observer((props) => {
  const state = useMemo(() => new State(), [])
  const onLoaded = action((widgets) => {
    state.widgets = widgets
    state.status = 'loaded'
  })
  const onClose = action((widget) => widget.status = 'animatingOut')
  
  if(state.hasActiveWidgets()){ // this causes rerender, whenever this function result changes (if state was changed inside action or runInAction)
    // something
  }

  ...
})

Also, you can put mobx state into react context and share it with multiple components. This way it could work similar to redux store.

like image 81
Daniel Avatar answered Dec 08 '25 22:12

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!