by zero_shift · 9y ago · 0 comments
I recently inherited a moderately sized Redux app with over 1300 source files! It's not a trivial app but it's not a word processor or videogame, either...
I'll also post a link to the slides and livestream video for my React Boston talk this last weekend, where I talked about the Redux ecosystem and gave an overview of useful Redux libs that can help with various use cases: http://blog.isquaredsoftware.com/2017/09/presentation-might-... .
Tell that to the previous developer. To be blunt, if your library isn't very usable without helper utils or wrappers, it probably isn't really doing its job.
This is my first time using Redux, and my experience has been quite negative. This project has so many reams and reams of code that just doesn't clearly _do_ anything. Line after line of throat clearing and pseduostructure.
I accept that this may just be a poorly written application. I've looked over the Express code and that's not much better, which is remarkable given that all it does is proxy API requests. But all these action creators and reducers and constants seem to have added a lot of indirection to what is still thoughtless and illiterate code.
We are seriously talking about rewriting the whole thing. For a one year old project that's quite damning. Can you point me to an open source codebase that might convince me Redux-done-right makes for readable code?
Not coincidentally, most blogs about Redux jump right into how to use it, without prefacing it with why would you want to use it in the first place.
A lot of developers think introducing more libraries and more rigor is a good thing even if it drives up the cost of software development. This is the only reason I can think of, for why so many people are using Redux. Another reason may be ReactRouter which makes it harder to supply data to React. But there are other MVC routers that make using React painless and I'd recommend to anyone considering using ReactRouter/Redux to consider better MVC-based alternatives. (And no, using MVC does NOT imply two-way data binding.)
I do agree that many people and articles talk about the "how" rather than the "why", but I'd say that this is a widespread issue rather than being specific to discussions of Redux.
Dan Abramov, Redux's creator, has said himself that "Redux is over-hyped". I also agree that many people are being pushed to learn it without understanding why they ought to use it, and that new learners are being told they _must_ start with Redux and React at the same time. That's not what we encourage officially - we suggest that people start with React first, then learn Redux later.
However, I think saying "people only use Redux because it's hyped or they're told to" is both inaccurate and unfair. I've talked to many people who have said that Redux is helping them write better-architected applications that are more maintainable and easier to work on. Some people may have chosen it due to hype, but many others have chosen it because it solves their problems.
Finally, I'd like to recommend reading Dan's article "You Might Not Need Redux", which discusses the tradeoffs involved with Redux, both the limitations it asks you to follow and some of the potential benefits you get in return: https://medium.com/@dan_abramov/you-might-not-need-redux-be4... .
Specifically, 1) it makes rapid iteration simpler because I don't have to click back to the portion of the app that I'm testing but can instead just rehydrate a cached state, and 2) it makes it trivial to save state for the user either by caching it locally in the browser or by sending it over to the back end.
Even for those small applications/prototypes, having a centralized store allows me to code on auto-pilot where I don't have to worry as much about the code and focus on what it does instead. Would X particular piece of UI work better in a different way? Okay, then that UI code can fuck right off; it's not like it's going to affect the rest of my application's state.
I used a Flux library before but like mobx now and will default to that unless some specific requirement point to redux or something else.
I've touched probably 200+ production frontend apps of various sizes by now, ranging from a couple of pages, going to tens of millions of lines of Javascript in a single monolith.
Your millage will vary and everyone hits different challenges in their career, but to me, the biggest issues when building apps was never building them from scratch or adding new features. It was always maintaining existing features. So I optimize everything I do for that, as I consider everything else completely trivial except for groundbreaking algorithms designed by PhDs (which is not me) and not worth thinking about.
I've spent years trying to nail down why these apps, no matter who works on them, always end up impossible to deal with. No matter how much time is spent trying to figure out the architecture, documentation and design, it always goes to hell given enough time.
To me (and its a totally personal analysis), it was always nailed down to figuring out: "Where the F* does this value come from" or "how do I follow what the hell this button does". It should be simple. I can use a debugger, obviously, but as requirements pile on, it invariably goes to hell.
Elm, to me, is the panacea of solutions here. A single atomic state, and a UX that is nothing more than a projection (or a map, if you prefer) of state to UX.
And to keep the UX "dumb", you then need to externalize all state and side effect logic.
Once you have that, you can reason about any bug without even looking at the code. Is the UX wrong? Was the state right? No? Did the event triggered right? yes? Well, the bug HAS to be in the update function. Boom done.
Now the question becomes, how do you reproduce this in JavaScript, which doesn't even have an approximation of algebraic effects, doesn't have immutable data structures, doesn't have a good way to play with the dom in a declarative way...
React + Redux with a few extras from the ecosystem provide that. Who cares about boilerplate, I get predictability. The more you abstract, the less predictable things get and bugs can come from anywhere.
Inevitably as the app grows, you need to add stuff and weave it in the existing features. The decoupling of State <--> Selector <--> Component <---> Action <---> Reducer has a very tightly defined set of semantics where even the most complex requirement fall neatly in these atoms (not quite as neatly as Elm when it comes to side effects, but it's as close as I've found for now).
Build an app some other way that does the -exact- same thing? You'll either end up with just as much code (oh, it won't be as repetitive and boring, but it will be there. I LOVE boring code), or you'll end up with something much more rigid that requires more compromises. There's a few alternatives that get close, but they usually do so by tightly coupling concerns and making it harder to figure out where the hell shit is happening.
The only obstacle is that the reasons behind "why" things are done this way is almost lost to most people working with Redux, in spite of Mark's best effort to prevent it from happening (there's only so much he can do short of brainwashing the planet). When the "why" gets lost, the community starts building things that neuter Redux, making it seemingly useless vs the alternatives.
The TL;DR is Redux tries to place a set of constraints on how and when you're allowed to share state between components and how and when you're allowed mutate that shared state, much like how React and it's virtual DOM abstraction places constraints on how and when you're allowed to manipulate the DOM.
These constraints allows the library to make certain assumptions about state and state changes that enables it to perform global performance optimizations across the entire codebase (namely performing only shallow equality checks on all state-mapped props when determining whether or not to rerender, because it can assume all state changes will result in a reference change) that would otherwise have to be performed for each component on a case by case basis, and micro-optimized by each individual developer by hand.
These constraints also allows tooling authors to make these same assumptions, which is what enables the best-in-class tooling that Redux developers have access to, like time traveling debugging and state change replays. These tools would simply not be possible to build in a generalizable way if your codebase didn't allow them to make the same assumptions (and adhere to the corresponding constraints when it comes to state sharing and state mutations) as it could for a Redux codebase.
The post has a whole list of very compelling use cases/tooling that are either made possible by or at least made completely trivial by the enforcement of these constraints around state mutations:
> These limitations are appealing to me because they help build apps that:
> Persist state to a local storage and then boot up from it, out of the box.
> Pre-fill state on the server, send it to the client in HTML, and boot up from it, out of the box.
> Serialize user actions and attach them, together with a state snapshot, to automated bug reports, so that the product developers can replay them to reproduce the errors.
> Pass action objects over the network to implement collaborative environments without dramatic changes to how the code is written.
> Maintain an undo history or implement optimistic mutations without dramatic changes to how the code is written.
> Travel between the state history in development, and re-evaluate the current state from the action history when the code changes, a la TDD.
> Provide full inspection and control capabilities to the development tooling so that product developers can build custom tools for their apps.
> Provide alternative UIs while reusing most of the business logic.
You could certainly make the case that Redux is not necessary for building a React app. Or the case that the additional boilerplate and constraints it places upon you could be a net negative for apps that are not sufficiently complex to warrant them. In fact, that's exactly the case that the linked post tries to make.
And yes, the only reason people use Redux is to introduce rigor (constraints) into their codebase and development workflow. But to insinuate that the rigor and constraints introduced by Redux will only ever be a net negative in terms of developer productivity is to display a fundamental ignorance regarding the vital role that rigor and constraints have always played in software architecture, and the fact that the recent advances in frontend architecture that have been proven to reduce complexity and make large codebases easier to reason about (things like the virtual DOM, unidirectional data flow, immutable state trees/caches, functional/reactive programming, and even the MVC pattern itself) have almost always come as a result of placing more constraints on what the developer is allowed to do.
There's a commonly repeated phrase that "Redux is a pattern, not a framework". Redux doesn't have anything built in for actually updating the state, or defining an application architecture. Redux primarily provides a pattern for separating the write logic from the rest of the app conceptually, and adding centralized behavior on top of that via middleware and store enhancers. So, how you build and organize your application around that pattern is up to you.
Similarly, Redux does not _require_ that you use action creators, action type constants, or that you separate everything into multiple files by code type. Those are common _conventions_. It's absolutely legal for a Redux-connected React component to do:
this.props.dispatch({type : "ADD_TODO", text : "Buy milk"})
However, there _are_ reasons why those patterns exist in the first place.So, a few thoughts. First, I'd encourage you to take the time to read through my two-part blog post "The Tao of Redux" [0], which goes into detail on the history and design of Redux, the intent for how it _should_ be used, and why common usage patterns exist.
Second, while I don't have a specific Redux codebase to point to as a "shining example of best practices" strictly off the top of my head, I do have a list of some selected Redux applications that may be worth looking at. Some of them are purpose-built examples, and others are "real" apps. See the list at [1] - I know that there's some good codebases in that list. I'll also suggest taking a look at "Project Mini-Mek", the sample application for my own blog tutorial series [2].
My React/Redux links list has a large section of articles discussing good Redux architecture and best practices [3]. Some of those articles might be helpful.
Finally, I'd be happy to spend some time discussing your current app's codebase, and perhaps offer some suggestions on ways you can make it better or easier to deal with. HN isn't a good place for that. However, I spend most evenings hanging out in the Reactiflux chat channels on Discord. Please feel free to ping me there, and we can discuss things further. The invite link for Reactiflux is at [4].
[0] http://blog.isquaredsoftware.com/2017/05/idiomatic-redux-tao... , http://blog.isquaredsoftware.com/2017/05/idiomatic-redux-tao...
[1] https://github.com/markerikson/redux-ecosystem-links/blob/ma...
[2] https://github.com/markerikson/project-minimek
[3] https://github.com/markerikson/react-redux-links/blob/master...
It seems like it is essentially trying to bring functional union type case switching to a language without that feature. As such, actions are insanely laborious to construct. Furthermore React / Redux is far to pedantic in reinforcing it's design decisions without offering a backdoor to work interact with the outside world.
https://github.com/erikras/ducks-modular-redux
I'll also point out that those tools are all listed in my Redux Addons catalog at https://github.com/markerikson/redux-ecosystem-links , albeit nested inside the different category pages, and I did just highlight them all in my ReactBoston talk over the weekend (slides and video at http://blog.isquaredsoftware.com/2017/09/presentation-might-... ).
I ended up making a dead-simple merge(oldObj, newObj) function that's halfway between Object.assign({}, ..) and lodash.merge() (it doesn't merge arrays)[0]. It makes it easy for me to update deeply nested state trees, provided the nested data is simple enough.
As a result, 99% of my dispatches uses one action type, PLAIN_MERGE, and a dumb state tree indicating what I'm updating, like so:
const handleChange = (values) => {
dispatch({
type: PLAIN_MERGE,
state: {
scatterPlots: {
plotSettings: {
[selectedPlot]: {
[axis]:
clipValues: {
lowerBound: values[0],
upperBound: values[1],
},
},
},
},
},
},
});
};
That might be some deep nesting, but it actually reflects the structure of the interface too, so it's kinda self-documenting.The associated reducer is simply return merge(state, action.state). Again, maybe I'm missing something but it seems like a pretty simple and effective solution to me?
[0] https://gist.github.com/JobLeonard/c4292594ce4d439ab20ec109f...
There's actually prior art for what you're doing (per the articles at [0] and [1]). The code will work, and the changes should show up in the Redux DevTools. Dan even described that as a possibility in some of the earlier Redux issues ([2], [3]).
Now, having said all that: I _personally_ would say that a "single SET_STATE action" approach goes against the intended spirit of Redux. One of the core principles behind Redux is that it should make it very easy for you to understand when, why, and how your state was updated, and what part of the application triggered that state update. If you only have a single SET_STATE action type, then reading the action history log in the DevTools won't tell you much useful. You can see the action contents and the diffs, but the action log itself won't have any semantic meaning, and you can't easily trace back to where the action was dispatched because the entire codebase is dispatching the same action type.
Redux also doesn't care if you do "setter-style" action naming like SET_USER_NAME and SET_USER_ADDRESS, or "event sourcing"-type naming like "USER_ATTRIBUTES_UPDATED". However, either of those approaches is going to at least provide _some_ semantic meaning, making the action log easier to read and the origin of the action easier to trace.
I'd encourage you to read through the "Structuring Reducers" section in the Redux docs [4]. In particular, the "Normalizing State Shape" page [5] talks about why we recommend normalizing your data into a flatter structure, rather than keeping it nested.
Finally, you might want to read through my two-part blog post "The Tao of Redux" [6], which goes into detail on the history and design of Redux, the intent for how it _should_ be used, and why common usage patterns exist.
[0] https://medium.com/@jeswin/implementing-redux-is-tedious-but...
[1] https://medium.com/@benevolentNinja/minimal-redux-setup-e6a1...
[2] https://github.com/reactjs/redux/issues/155#issuecomment-113...
[3] https://github.com/reactjs/redux/pull/140#issuecomment-11395...
[4] http://redux.js.org/docs/recipes/StructuringReducers.html
[5] http://redux.js.org/docs/recipes/reducers/NormalizingStateSh...
[6] http://blog.isquaredsoftware.com/2017/05/idiomatic-redux-tao... , http://blog.isquaredsoftware.com/2017/05/idiomatic-redux-tao...
> when, why, and how your state was updated, and what part of the application triggered that state update.
Well, when I said "single" action I was fudging a bit; I have a switch statement with a dozen action types that all are equivalent to the PLAIN_MERGE action. The point is more that I don't have much code inside my actions and reducers, except for the stuff that needs to see the "whole program state" - everything else tends to be encapsulated inside the components.
Also, I think you overstate the lack of semantic meaning: that state tree I pass along, together with the occasional custom action type tag, tells me exactly where the dispatch originates from. Of all the problems I have when debugging my app, finding the source of the dispatch is never one of them.
- I don't already understand how an app using redux works when it reaches a decent size; therefore don't know what problems it will have and need to learn more
- I can't start using redux to understand those problems without making important architectural choices early on, i.e. between sagas/thunks, ducks/not-ducks, or how to remove duplication from reducers, because the community has so many parallel solutions to any given problem; therefore, I need to write a toy app instead of using it on a real product
- redux on its own seems to need about ten packages before you can load information from a json api and pass it to react, a task which is the basis for most toy apps; therefore, every toy app I write seems bloated and heavyweight
It's a hard ecosystem to bootstrap yourself into.