by stupidcar · 8y ago · 0 comments
The reason is that while you may be able to break up your HTML into a composable hierarchy of purely-functional components, the actual data and state you need to distribute to them has a structure that is completely unrelated to how its laid out in the DOM. In a complex web app, a component nested twenty levels deep may need to display pieces of information, like the user's date of birth and the current temperature on Mars, that none of its parent controls cares about.
At that point, you can either bite the bullet and pass state through layer upon layer of props, completely eliminating any semblance of separation of concerns in your component layering, or inject state into your components via some other mechanism, like Redux/MobX/Context. At which point, JSX is basically just another fancy HTML templating library.
"Idiomatic" React is a fun game to play when doing basic examples, using something like a todo manager, but as soon as you're in the real world, you hit its limitations very quickly.
Sadly it seems that's mainly been cargo-culted. It's not the case that React+Redux is the equivalent to say Angular, but by some unfortunate accident due to Facebook's announcement of Flux, and then the hype around Redux as a 'better Flux', people started assuming React+Redux is what is needed to build a React app.
Meanwhile Dan Abramov, Redux creator says [1]:
> Flux/Redux is meant for big apps with complex nested UIs that have many independent parts but share common caches of data.
That's not "every semi-complex React app". In most "semi-complex React apps", most state can be derived from the route (e.g. react-router) or is relatively local. Redux is not required.
[1] https://twitter.com/dan_abramov/status/732719257579065345
As developers we can't all be building tools. We choose tools that others build for us, so that we can get our job done. Soemtimes I'm interested in going "one layer down" and build tools, but it's almost always a distraction; we want off-the-shelf products like React and Redux. We need to pick stable tools that promise some sort of longevity. We also need to pick tools where best practices and idioms have been established.
To do this we have to trust someone else's opinion and try to gauge which solutions have the best prospects. This means not just evaluating software based on its own technological merits, but also listening to what "the community"/"the industry" seems to be rallying around; you don't want to be stuck using a library that nobody is maintaining, just as you don't want to be stuck using something that's just badly designed.
When we started using React, there was no state management framework available, and everything was handled somewhat ad-hoc. Then Facebook described Flux, and we realized they were onto something, so we started using their patterns, with some simplifications where theirs seemed overly complicated. Then Redux came along and seemed like a better way to do things.
At each point there was uncertainty about what best practices and "idiomatic" solutions would turn out to be, because the technology was immature. I don't think anyone was cargo-culting. It was just that a lot of people were busy trying to create things, and when there isn't clear guidance, and the alternative is going back to Backbone or jQuery or something, then you just forge ahead, trying to do fit the pieces together.
Can you really look at where the community is, the perception that still exists that React+Redux is necessary, projects like redux-form (that now admit Redux was a poor fit for forms) and honestly say no cargo-culting happened?
Sympathy for 'attempting to follow the mainstream' though, I understand that. Personally I stuck with Backbone for years longer than most, avoiding the Angular/Ember wars, and the early days of React+Flux til the React ecosystem had matured a little, before jumping over to React at which point it was clearer that Flux/Redux were being misused.
The claim isn't that there's no cargo cult around the React ecosystem — but not everyone writing React code is approaching it with experience, which means they try to pick up best practices from other people. That's not "cargo culting"; it's a reasonable thing to do when you have to solve a problem you don't know how to solve!
Ultimately, people aren't being "tricked" into using these tools. They proliferate because they solve real problems people have, and a lot of people would rather work with a popular and well-documented solution (with known advantages and drawbacks) than trying to forge their own path and seeing how it goes.
I never got the impression, even from the start, that setState() was a good solution, by the way. But it's not like the React authors were completely sure of where the right design was, either. Flux, for example, as it was originally described, appears completely overdesigned at this point. The good design is to be found in Relay and GraphQL.
I also spent just 1 hour completing multiple RFCs in another app built with create-react-app using redux/connect as a purely syntactic-sugar state propagation layer.
I love the complexity and feeling of fulfillment for triumphing in the former scenario, but it is definitely much more of a distraction than anything else.
IIRC there were a lot of comments about having to pass props to children constantly (without using a state management library). Seems like it's a lot easier to not use a state management library now that an official, non-experimental Context API exists. But remember, this was only added a few years later.
Redux also offered a simple approach to the "action bus" idea from Flux, but omitted first class async support, etc. React itself also somewhat overlooked async patterns, which created the idea that their absence was by design and so an additional (opinionated) library was appropriate.
In sum I'd argue that React actually fights against js quite a bit and that it will truly come into its own once reason gets more mindshare.
For those of us who invested heavily in react as all this was becoming clear (and being ironed out) I hope we learned enough to allow better decision making in the future.
Also, React has a few "on by default" performance enhancements that are a bit conceptually confusing and create something of a mismatch with the functional approach.
But still it's difficult (and unpleasant) to imagine the world without React.
It took me many years to realize this. I think very few front end developers understand this. And more problematically: very few framework devs seem to understand it.
Stated another way....
Your tree of UI widgets, and
Your tree of data which feeds those widgets
... are two orthogonal trees.
If you are a front end dev and you haven’t spend time wrestling with that, I strongly recommend it. It’s extremely likely your front end architecture is suffering because of it.
React take the strongest stance on this matter, by making the interface to every widget be one giant shared global. But globals are bad, so while it’s good they acknowledge the situation, they mostly punt on the question of how to deal with it.
>Your tree of data which feeds those widgets
Not with a well-designed XML format and XSL-T! But hmm, nobody seems to use that anymore either.
You either really got it and then could do wonderful things, or you sorta muddled along with it and it was ok but it was like they were wearing a straitjacket.
I made a pivot table control out of it, with almost all the logic inside the XLST, it was amazingly fast compared to IE6's javascript at the time. I remember that Blizzard used it for the WoW online character viewer which was streets ahead of what anyone else was doing.
Also there's a DailyWTF about someone doing this on a large app, which brought the developer out of the woodwork to defend it who said in fact it wasn't a WTF, it was deliberate, it worked, loads of people loved it. Which prompted a huge debate about how it was actually kinda good, but just too high a learning curve (which is the death knell of many a tech).
Personally I don't miss it. The best way I can sum up XML/XLST up is that it made me feel clever, and now I know that when I start feeling clever about my code that's a sure sign I'm making something that's going to be a nightmare to maintain.
Oh well, at least Web Components seem to finally be around the corner, a decade later.
Same. Long ago I replaced an expensive Crystal Report solution with reports delivered as XML/XSLTs that used IE's feature at the time of applying the XSLT at the browser. It worked very well and provided nice interactive reports. I also wrote a bunch of cookbooks (for lack of a better term) that allowed the business analysts to create additional reports.
Pierce? Is that you?
One thing to realize is that you always get to decide on the granularity of your compositions. It is not necessary to build a deep hierarchy if you design the granularity of your interfaces correctly. Another great tool is higher order functional programming, such as passing components to components (via children). In this way, it is easy to describe generic interfaces and supply specific pieces of data without having the intermediary interfaces know or care about that data. Another approach, akin to using something like the state monad, is to use Reacts context feature, but this is rarely needed, in my experience.
Personally I make heavy use of higher order components, and I find I rarely exceed a component tree height of three.
Right now with a few devs it is going very well but I do worry about on-boarding people who are not proficient in functional programming.
React code without a global state management library is very pleasant and easy to read/understand for many, but for some it is not always obvious to write. You may have to spend more time code reviewing and training newcomers who will sometimes feel like their task is impossible without Redux. I have yet to see if those requirements can still hold for a big team but I think it is possible.
My current opinion on Redux is that it is best suited for existing project migrating to React because you may inherit very odd relationships between the view and the data and Redux will avoid you a lot of pain on this regard. A new project should avoid Redux & co as long as it can.
That's my experience as well. If you use a deep component hierarchy you have bigger problems than those solved by Redux, VueX or the Context API.
Higher order components or even simple functional components are really underrated when it comes to making your application simpler to reason about and to maintain.
Examples of HOC are the connect() call from Redux, or the withNavigation() from React Navigation, or injectIntl() from React-Intl. These respectively add Redux functionality, navigation functionality, and internationalization functionality to your component.
I think the name "Higher Order Component", like many things in the React world, is poorly chosen and actually obscures what it is, how it works, and makes it look more intimidating than it really is. It's technically correct (like 'reducer' is), but communicates nothing.
It's effectively a replacement for the old React mixin system.
It happens to use functional programming methods, but that's an implementation detail.
> At which point, JSX is basically just another fancy HTML templating library.
JSX is optional syntax sugar; my team uses React and Redux heavily, but we've opted not to use it.
HTML templating is great actually, all the rendering is data -> UI.
If you go back to the early Rethinking Best Practices presentation[0], it boils down to asking why client side development isn't like like HTML templating. The answer is that updating the entire page DOM on every change is unworkable, there needs to be support for partial updates. That's what React offers, a return to the data -> UI paradigm, without having to write a secondary code path for partial updates.
dom.div({ props }, ...)
For our own components, we export the output of React.createFactory https://reactjs.org/docs/react-api.html#createfactory rather that the component itself, so rendering code looks like: MyComponent({ props }, ...)
I realise that both of those are marked legacy, with a nudge towards using JSX instead, but they are pretty thin wrappers around createElement so it seems like a small dependency.Having a shared store really does change the way you look at web apps - it's almost a completely different paradigm. If you can avoid re-loading the data for a view if you already have it then then opening a new view to edit a subset of the data instead of dealing with popup makes life so much easier - you get a lot more freedom with the UX and going back to the previous view with the parent data is almost zero-cost.
The vast majority of our codebase is comprised of simple idiomatic React components. Our reducers and glue code (e.g. @connected containers) are a very small portion of the codebase. If I woke up tomorrow and decided Redux was the source of all our problems I could completely remove it while only needing to refactor a small portion (<5%) of our codebase that's mostly boilerplate anyways.
I don't understand your point that injecting state into your components (e.g. with Redux' connect function) means JSX is just another fancy HTML templating library. All you need to do is have your React component export a "dumb" version as well as a connected version. Your dumb version will still be reusable in other parts of your application, and any other application could also use your dumb component and connect it to their global state through whatever means they please.
There's your problem I think, as other sibling comments pointed out.
I understand that such an open-ended product is frustrating to use because redux is insanely overengineered, mobx reintroduces data binding, and context is buggy and terrible, but I don't think what you're calling "idiomatic React" is actually considered idiomatic by anyone, including the core development team.
Interested in hearing what you think, though. My Redux experience has been more limited by trying to avoid it on small projects.
First, your points about `dispatch` and `context` are specifically about the React-Redux bindings, not the Redux core itself. React-Redux is specifically intended to act as an abstraction layer so that your own components are "unaware" of Redux, which keeps them more reusable and more testable. It also saves you from needing to write store subscription handling every time you want to make use of data from the store. My "Redux Fundamentals" workshop slides [0] show examples of what it would look like to hand-write store subscription code all throughout your UI, and it would be a pain.
If you _really_ want to, there's nothing stopping you from importing the store globally across your application and using it, but that misses out on the benefits of React-Redux, and also ties you to that one specific store instance.
Second, you can absolutely do async logic without any middleware. However, one of the key design points of Redux was to allow users to choose which approach they want to use to handle async logic, without limiting users to whatever was built in to the core. I discussed this in my "Redux Ecosystem" talk at ReactBoston last year [1].
You can certainly do async logic without any special middleware - just `connect()(MyComponent)`, throw in a `setTimeout`, and call `this.props.dispatch()`. The point of `redux-thunk`, the most common async middleware, is that it provides a generic way to move async logic outside of your UI and make it reusable [2].
Finally, the "dispatching an action === calling a function" comparison can be true, but only if you're using Redux with a limited mental approach and treating actions like "setters". If you start thinking about actions as more of an "event that occurred", then that leads to having multiple parts of your reducer logic independently respond to the same action and update their own pieces of state (which is an encouraged usage pattern). Justin Falcone had some good thoughts on this a while back [3], and I talked about this some in a fewmore of my blog posts [4] [5] [6].
[0] https://blog.isquaredsoftware.com/2018/06/redux-fundamentals...
[1] https://blog.isquaredsoftware.com/2017/09/presentation-might...
[2] https://blog.isquaredsoftware.com/presentations/workshops/re...
[3] https://medium.freecodecamp.org/whats-so-great-about-redux-a...
[4] https://blog.isquaredsoftware.com/2017/01/idiomatic-redux-th...
[5] https://blog.isquaredsoftware.com/2017/05/idiomatic-redux-ta...
[6] https://blog.isquaredsoftware.com/2017/01/practical-redux-pa...
It’s easy to point out frustrating things or hard problems; it’s not easy to point to a way out.
Personally I love the explicit state flow react forces, and I would hate to move to a framework where I spend time figuring out how data goes from point A to point B.
Redux is what you get when people try to use React as a "full-app" framework instead of what it's meant to be: a view layer.
Is Redux not exactly that?
Your application's state should live outside of React, and be passed in as the root's props.
Redux should have your application state, and any UI state should be in pure React (portals, context, etc).
Redux -> app data React -> UI
Ironically, Redux came out around the time Angular popped. While not everyone, a significant portion of early adopters came in because they were rejecting the Angular 1.X way of handling state, and Redux was the polar opposite.
You build a DataSource class/prototype with methods such as :
- fetch
- addChangeListener
- removeChangeListener
You extend this class for each data type :
class CommentsData extends DataSource {
// Your custom data source with your data treatment and data getters
}
And you use the Higher-Order Component pattern: https://reactjs.org/docs/higher-order-components.htmlI'm not a fan of Redux either, but I fail to see what problems this approach solves.
Isn't a good chunk of AirBnB, Facebook, Instagram, Netflix, The New York Times and Dropbox written in React?
The built-in state management has limitations, of course. I see it best for keeping state relevant to display-- React is supposed to be a "view" library, not a state management one.
Because React = state to DOM while Redux = how to get from previous state + action to a next state? :)
They do different things.