Wow, I just tried to tag this post with mobx
, but no suggestion..
I want to make a comparison between Redux and Mobx. Here are my contrived simple apps showing notifications.
// shapes
type Store = {
notifications: Notification[],
setNotifications(notifications: Notification[]): void,
prependNotification(notification: Notification): void,
}
type Notification = {
content: string,
}
As shown above, the shape of main store and the display is very simple and contrived.
The app is showing all the notifications with contents.
Two behaviours:
- set initial notifications
- get the latest notification and show on the top
Mobx solution
The key here is useNotifications
hook which exports useContext
result with an observable managed by MobX magic
const store = observable({
notifications: [],
setNotifications: action((notifications) => {
store.notifications = notifications;
}),
prependNotification: action((notification) => {
store.setNotifications([notification, ...store.notifications]);
})
});
It's very easy to think of and use. Just simply call useNotifcations
hook anywhere you want to get hold of the actions or notifications data.
Only thing you want to keep in mind
Use observer
to wrap your component otherwise the component will not react to the change! like observer(NotificationList)
Redux solution
I think we should skip the setup part like wrapping the app with Provider
and combining reducers.
The key part here is notification reducer and how to change the state via actions. That said, we have to keep the action -> reducer -> state
in mind all the time while using redux. That's something I don't like.
To make all things working, boilerplate is needed. You have to setup actions in unique names, setup big switch statement to distribute the reducer logic.
To fire an action in component, it's much easier now. The only thing you need is useDispatch()
.
To use a state in component, simply use useSelector()
to get hold of the piece you want from root reducer.
My recommendation
Use MobX, it's much easier and straightforward. You define the shape you want in store, then easily get hold of and easily make change of it.
By using Redux, you need to have the action, reducer flow in mind. Also if you're using typescript, oh.. you might need to have a lot more boilerplate.
Maybe Redux does have a larger community which may provide more support and maybe more tools for Redux. But still, I like MobX more.
Top comments (0)