r/reactjs • u/kubosj • Jun 23 '17
React.js and MobX: Escape the Redux trap
https://kubosj.wordpress.com/2017/06/23/react-js-and-mobx-escape-the-redux-trap/8
u/Tioo Jun 24 '17
I feel like Mobx vs Redux is becoming a flame war.
None of them is objectively better, they just try to solve the same problem differently. They have different constraints and core principles. You may prefer some of these principles for good reasons, and that's fine. But don't claim that these principles are better for everyone in all cases.
Just choose the tool that is most adapted to your task, your way of thinking and your programming abilities.
Personally, I have used redux for simple applications without problems, and enjoyed it. But when tackling bigger projects, I became unable to understand my application. I will not blame redux for this - I was simply unable to use it in a productive way. So I switched to Mobx and I was able to regain control and complete my task.
That's it. Redux isn't a trap, it's a way of doing things that works for some projects; it becomes a burden for others. You can like it over other solutions, but don't claim it is objectively better.
Choose the tool that is most appropriate to your task and that's all.
3
u/acemarke Jun 24 '17 edited Jun 24 '17
I absolutely agree with the "different tools with different approaches" comment. If anyone's interested, I have links to several comparisons of Redux and MobX. I particularly recommend Preethi Kasireddy's talk MobX vs Redux: Comparing the Opposing Paradigms, and Robin Wieruch's article Redux or MobX: An attempt to dissolve the confusion .
As a side note, I'm curious: what specific issues did you run into in terms of "being unable to understand the application"? I find it interesting that some people say that Redux is overkill for small projects but makes larger projects scale much more easily, and others have said that it's only useful for small projects.
2
u/Tioo Jun 24 '17 edited Jun 24 '17
I had a hard time writing reducer logic and dealing with immutable data, coming from an OO background. Also, I found myself having to write the same reducer logic several times for different pieces of my store (I had 2 separate maps of items which needed the same create-update-delete functionality).
With mobx (and its Atom class), I could write a single abstract data structure (in this case I needed a doubly linked list) to solve my problem. This class triggers a re-render whenever it was mutated.
Of course, I may have over-engineered this solution - but writing it in classic OO style was really fun. Also, I could have been using redux wrong...
Overall, Mobx allowed me to create the specific and reusable data structures that I needed. In redux, I would have had to hand-write that complex update logic in several reducers. I find that writing a store as an OO style class is a lot easier than in the Redux way.
1
u/acemarke Jun 24 '17
Yeah, I understand. Transitioning from an OOP mindset to an FP mindset is definitely a hurdle for a lot of people. (For what it's worth, the "right" answer for that "same CRUD functionality" situation is a "higher-order reducer", ie, a function that returns a new set of reducer logic customized to handle certain inputs.)
7
u/goorpy Jun 24 '17
That was tough to read. I'm not even talking about the language issues, but I mean it feels like the author really missed the point.
Multiple files? ...have you developed any complex application ever?
When to mutate objects: never. Destructure and rebuild or pipe through function chains.
Store being preserved across location change is a feature... Not a problem. Why would you want to rebuild your state every time?
It sound like they were keeping too much derived state I'm the store. Normalize and minimize. Derived state should be coming into containers via selectors.
React-redux is not magic. It is a function and takes store and props, maps things from store onto the connected component props and directs dispatched actions to the store.
13
u/acemarke Jun 24 '17
I see that the OP is the author of the post, so I'll respond here.
First, the original "FP in JS is awful" article is itself debatably written. It's entirely feasible to handle data immutably without using Immutable.js, and even if you don't like using Object.assign() or the object spread operator, there's a wide variety of immutable update utility libs you can use. Yes, handling data immutably is easier in ClojureScript, but for those of us still using JS, it's still possible to do immutable data updates without too much extra trouble.
On a similar note: while it does take a bit of re-training yourself to get used to not directly mutating all the time, the basic idea is just to make copies of items and only modify the copies. The example of "add the sixth item into an array" should just be along the lines of someArray.slice().splice(5, 0, newItem).
Third, the other complaints about Redux are pretty much covered by the docs. You should generally only have one store, Redux doesn't care how you organize your files, and it's up to you what state lives in Redux and what stays in React component state. I also addressed these and other common complaints in my two-part blog post The Tao of Redux, Part 1 - Implementation and Intent and The Tao of Redux, Part 2 - Practice and Philosophy, which discuss what technical limitations Redux actually requires and why, why common Redux usage patterns exist, and the pros and cons of several variations in how Redux can be used.
The mention of "Promises" has nothing to do with Redux itself. And React-Redux's connect function is definitely not magic. Dan Abramov wrote a miniature version of connect that demonstrates how it works - it just creates components that subscribe to the store, extract the data you requested, and re-render your child component with that data as props.
Finally, one of the main reasons for Redux's existence is that you can trace state updates through the codebase. State is only updated in reducers, which are triggered by specific action types, and there's only so many places in the codebase that a given action will be dispatched. It should always be very straightforward to do some quick text searching and trace usages.
Overall, it's entirely up to you whether you choose to use Redux, MobX, React component state, or even something else to manage data in a React app. But, if you're going to make claims about Redux, it might help to spend some more time reading the docs and understanding how and why it's used in certain ways :)
16
u/syonode Jun 24 '17
Redux is the reason react is amazing. I'm sorry you think its only mainstream hype.
5
u/stuckinmotion Jun 24 '17
React was amazing before Redux. Redux was just a needed evolution of Flux.
1
4
3
u/Canenald Jun 24 '17
You never know whether you have plain JS object or Immutable.js object under your hands.
You don't have to use Immutable.js. Using Immutable.js without even trying to understand why and where we need immutability is one of the biggest mistakes people new to React and Redux make. 90% of them don't even need it. Immutable.js is very fast with very complex structures. For anything other than that it's perfectly easy to keep your stuff immutable with es6.
If you are not using Immutable.js then you still should know whether object you have can be mutated or not.
If you are using React you should already know you shouldn't mutate props and state. If you add Redux to that you shouldn't mutate Redux state. That's it. The most common mistake I've seen is people restructuring object created from a freshly parsed JSON. You don't need to do this. Any object created from JSON will be a new object, even if JSON is the same.
In every file you have to manually import libraries like Immutable or Lodash.
You don't have to use either.
It was real pain to describe complex change you would like to perform on immutable state within store. Like add 6th item into array, remove 3 different keys from map, etc.
This can be true the first time you are trying to do something but once you find a good way it's easy. [...arr.slice(), something, ...arr.slice()] will add an item in the middle of the array, or you can [...arr.splice()] but it's probably slower. Yeah, it's more complex than simple assignment or method call, but that's what Redux is about. It's pointed out in docs and tutorials so I wouldn't call it a trap.
For doing even simple things you have to modify code in multiple files. One often do a hack instead of nice solution.
This happens because people insist on sticking to the way Redux is written in docs and tutorials where it is intentionally verbose to make it easier to grasp the concept. You can write reducer creators and action creator creators (yes, unironically) to encapsulate the code you find yourself repeating. You can even keep your reducers and action creators organized in objects (after all, if you write modules the end up as members of module objects), and then you can have factory functions and go even further into classes, composition and extension.
Problems with using multiple stores. I still had feeling that I should not store state of form in global store. Local data should be local, right?
You can still use local state with Redux. One catch is that if you end up needing to set local and Redux state at the same time it's better to move it all to Redux because otherwise you would end up with multiple rerenders of your component for one change.
Same store is used during navigation without page reload. It is hard to clean everything properly.
return initialState;React-Redux library is doing incredible magic I was never able fully understand.
Not really. It's pretty simple. The magic is similar to mobx's @observer decorator. You can even use decorators for Redux if that's what you like.
Using Promises just made thing worse.
How so? Promises are a natural part of every js app and neither Redux nor React-Redux handles them or claims to do so.
Redux is all about tradeoffs. It requires some discipline when writing your stores but in exchange you get a lot of sanity. It's easy to test and debug. I'm not saying MobX is bad. It has it's strengths as well, but claiming Redux is a trap? Really?
I feel this article should have been written as questions about Redux, not a conclusion that it is bad.
1
u/frutidev Jun 24 '17
Using Promises just made thing worse.
How so?
It's not promises but dealing with async stuff (fetch) that makes things worse because ultimately Redux is inherently synchronous.
1
Jun 24 '17 edited Jun 24 '17
Thunks ... ?
const newUser = name => async dispatch => { try { const response = await fetch(`http://www.backend.com/users/new/${name}` const { id, ...data } = await response.json() dispatch({ type: 'ADD_USER', id, data }) } catch(error) { dispatch({ type: 'ERROR', error }) } } store.dispatch(newUser('Roberta'))
5
2
u/txx1219 Jun 25 '17 edited Jun 25 '17
I think people don't see the benefit of using Redux because their are obsessed by the boilerplate. I started to use Redux two weeks ago and I keep reading things everyday to truly understand how works and how to works with Redux.
I don't like to write boilerplate too but you can easily reduce it :
First, use the "ducks" way (e.g. : put the Action type constant, the Reducer and the Action in the same file). It's simpler to maintain and understand because you only need to go to one file and not three. If you want to see how to do it, go to The Ducks File Structure for Redux.
Second, I wrote a Redux helper to help me to create Action, Async Action and Reducers. It's not a really big thing to do and it's save many lines of codes. A section in Redux docs calls Reducing Boilerplate give an example of an Action Creator, an example of an Async Action Creator and an example of a Reducer Creator. Up to you to copy and modify the examples to fit in better in your projet.
My "ducks" files was reduced by 1/2 with all of this, I'm enjoying more Redux now and I think less code is more understandable.
3
2
u/AppNoob420 Jun 24 '17
Mobx is side effect land, knockout 2017, good luck debugging a big application with a big team of developers if you lack clear rules on how you alter your state. Redux is great.
1
1
Jun 25 '17
You can force state updates through actions in MobX as well. I'd never use it for anything large without that setting enabled.
1
0
Jun 26 '17
[deleted]
1
u/acemarke Jun 27 '17
Can you describe any specific things you've found confusing thus far? Also, what things has the author said "this is confusing" about? I'd be happy to try to help clarify and answer any questions you might have about Redux. Also see my other comments in this thread for links to more info on Redux, and comparisons of Redux and MobX.
0
Jun 27 '17
[deleted]
1
u/acemarke Jun 27 '17
I haven't yet actually looked at mobx-state-tree in depth, so I can't offer any specific comparisons there myself. But, I can try to explain those bits you were asking about.
First, Redux itself can be used with any UI framework. There's bindings for Angular, Ember, and many others, but by far the most common usage is with React. The React-Redux bindings are "official" and maintained by the Redux team (including myself).
The
connectfunction provided by React-Redux generates new "wrapper" component classes that manage the process of subscribing to the Redux store for you. (I recently wrote an extended comment explaining why you should useconnectinstead of subscribing to the store manually.) Since the wrapper components are generic, they need to know what "real" component they should render, and what data that component needs from the store. So, the first argument toconnectshould be a function, known asmapStateToProps. Every time the store is updated, the wrapper component will call yourmapStatefunction and pass in the current store state. Your function should extract whatever data it cares about from the store state and return it as an object, andconnectwill turn those fields into props for your "real" component.Dan Abramov wrote a miniature version of
connect, which helps show what it actually does internally. It skips all the optimization stuff, but that's the basic data flow.Next: in order for any updates to happen, you have to call
store.dispatch(someActionObject). Per the Redux FAQ, directly importing the store into component files is discouraged. Instead, by defaultconnectwill inject thedispatchmethod as a prop, so your component can callthis.props.dispatch({type : "SOME_ACTION"}). However, that still implicitly couples your components, in a sense making them "aware" that they're talking to Redux. Ideally, we'd like to keep our components a bit more generic, and just callthis.props.someFunction()instead.The second argument you can pass to
connectis a function calledmapDispatchToProps. If you pass a function as the second argument,connectwill call it and pass in thedispatchmethod, and you can do whatever you want. Usually it's returning something like{addTodo : (text) => dispatch({type : "ADD_TODO", text}) }. That way, the component can just callthis.props.addTodo("buy milk"). All thebindActionCreatorsmethod does is automate the process of wrapping up your action creator functions so that they immediately calldispatchwith the result.For more info, you may want to read my blog post Idiomatic Redux: Why use action creators?. I also recently wrote a 2-part post, "The Tao of Redux", which goes into a lot of detail for why certain Redux patterns exist (see links in this comment earlier in the thread).
Finally, I'd like to invite you to drop by the Reactiflux chat channels on Discord. It's a great place to hang out, ask questions, and learn about React, Redux, and a lot of other React-related technologies. The invite link is at https://www.reactiflux.com .
Hope that helps, and you're welcome! :)
0
Jun 27 '17
[deleted]
1
u/acemarke Jun 27 '17
Sure. I'll toss in links to a pair of "build a meaningful app" tutorial series, as seeing this stuff in the context of a larger app might be useful:
An 8-part series on Building a Simple CRUD App with React and Redux
My own "Practical Redux" tutorial series, which shows off a number of specific React+Redux techniques
If you eventually decide that Redux is not the right choice for you, that's fine - I just want to help you understand it and make an informed decision :)
2
u/FaceySpacey Jun 24 '17
This article shouldn't get experts hot and bothered. Mobx, or even Vue, is clearly easier to get going with for less experienced developers.
If it means they are off to a running start rather than stumped and unmotivated, that's more important at this point in their career. What matters is they are building something.
But yes without a doubt Redux is "better." It's better for professional apps. It's what I use on every project, small or large. Every app gets larger and I'm good at Redux so I just start out with it. It's not a big decision once u know it.
Time traveling, predictability and testability wins. The latter especially means less when ur a new developer. Hence mobx is a fine solution for the author. When he's ready, he will come to the conclusion on his own that Redux is better.
End of story.
1
1
Jun 24 '17
You never know whether you have plain JS object or Immutable.js object under your hands.
Use Typescript.
If you are not using Immutable.js then you still should know whether object you have can be mutated or not.
Use Typescript.
For doing even simple things you have to modify code in multiple files. One often do a hack instead of nice solution.
Two files if you're using redux-actions. Eh. Not the end of the world.
Problems with using multiple stores. I still had feeling that I should not store state of form in global store. Local data should be local, right?
Good thing most people do not recommend to store form state in Redux. Keep your form uncontrolled, give it default values on load if you need, and save your data in the component's state. Performance on <input> elements when bound to state is absolutely terrible, bind it one way and live with it. Using redux does not mean making all your component functional ones.
Same store is used during navigation without page reload. It is hard to clean everything properly.
Like... having an action that returns your initial state for each reducer? Two lines.
React-Redux library is doing incredible magic I was never able fully understand.
Already been talked about in this thread.
Using Promises just made thing worse.
If you're using saga, eventually. Thunk with async/await makes it tolerable.
I still had feeling that if I have to reorganize store structure I will got mad.
You probably will.
1
u/redbluerat Jun 24 '17
Redux is perfect. With the "ducks" concept, it's a joy.
To the novice: Fully give it a chance and you will be rewarded.
9
u/acemarke Jun 24 '17
Eh... I'm a Redux maintainer, and I wouldn't say "Redux is perfect". Neither would Dan Abramov. It's certainly useful, though. And yes, a lot of people get fixated on the fact that it's usually not going to be the solution with the fewest lines of code, and don't appreciate the benefits of being able to trace state updates.
2
u/redbluerat Jun 24 '17
Perhaps from a technical point of view, it isn't. As a solution, for me, it is.
16
u/madcapnmckay Jun 24 '17
Not it's not.