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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With