by ilovecaching · 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.
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.
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.
> 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.
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.
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.htmlIsn'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.
So e.g. if you want to have a Leaflet map i.e. `this.map = L.map(...);`, Vue will automatically add reactivity to this property. Sometimes I had big problems with this behavior (or it was simply annoying), so I wrote vue-static based on ideas of the core developers:
https://github.com/samuelantonioli/vue-static
Now I can have big objects in the Vue component which don't get automatically tracked using the reactivity system.
- - -
A problem for many beginners:
Another problem with the reactivity system is that sometimes you have a route like `/employees/:id` and edit an object. But on abort, you want to rollback. One thing you always have to do is to copy the object you want to edit (I use lodash's `_. cloneDeep(obj)` for this). If you use Vuex, it's not such a big deal because it works using immutable state, but when you work with a plain javascript object this will definitely generate some headaches.
- - -
But otherwise, I think Vue is definitely the way to go. `v-model` can be seen as syntactic sugar while you have to add it to react inputs and textareas manually (using onchange and setState).
You can write stateless Vue code just fine and use JSX. On the other hand, React misses some of the cool features like the Vue component files (.vue files) and its templating language. And the best is: The framework doesn't say that you have to use it. It's not so opinionated but still feature-complete with the official plugins.
React is just JavaScript and HTML.
I personally find Vue templating syntax much easier to follow than JSX, but that's because I'm used to it. I honestly believe that's how React users feel about JSX too.
This is patently not so.
Vue has:
- three different html-like attributes
- three different scripting languages in templates (two Javascript-like, one Javascript, but only expressions)
- one scripting language for controller/model which actually breaks JS assumptions (about what `this` is, for example) by magiacally hoisting some (but not all) properties of an object
This is patently not so.
Maybe if you are used to JSX. - three different html-like attributes
: and @ are just shorthand for v-bind and v-on attributes.v-bind and v-on (and v-if) accept regular javascript, and it's not just expressions... you can use `active = true` to change a data value, for instance.
The only exception is v-for, as you mentioned, but it is close enough to ES6 for syntax to make sense, at least IMO.
- three different scripting languages in templates (two Javascript-like, one Javascript, but only expressions)
This is splitting hairs a bit, isn't it? Apart from v-for, you can write pretty much anything you want in the other two. - one scripting language for controller/model which actually breaks JS assumptions (about what `this` is, for example) by magiacally hoisting some (but not all) properties of an object
You mean the script part of components? Do you have any examples of that?At my last company we used `react-hyperscript` which was a simple wrapper around `react.createElement`.
Ultimately, the React developers made the mistake of making `createElement` so annoying to work with, I assume because they bought into JSX. Granted, JSX might have been necessary when React was first created in order to ease people into transitioning to HTML in JS, but I feel like we can move passed that now.
I highly recommend `react-hyperscript`: https://github.com/mlmorg/react-hyperscript
A translation from the JSX example that was the first (only?) example on the React homepage at the time:
https://github.com/jasom/parenscriptx/blob/master/example/co...
Furthermore, Elixir has Agent, a higher abstraction on top of Erlang/OTP gen_server that's easier to grok and use in many simple cases with no need to separate the public interface and OTP callbacks.
I think this is what the Flux model is all about, making UI code actually be a pure function of state. By that, I mean literally a function, where state is the argument, and where all you render depends solely on said argument.
If you want to change what is rendered, you send a message and a Store deals with the state modification. Once it's done, it calls your pure function again, this time with a different state, so you get a different render.
This IMO, decouples state and and view instead of tightly coupling it. Redux is the best Flux implementation to demonstrate this IMO because it puts all state in a single Store. The messages to this Store can come from anywhere: UI, server, me typing on the console, etc. The state changes independently of the UI and in fact I could have a full application without having a UI whatsoever. Or I could have a UI without knowledge of my state's topography, because Redux lets me morph and cherrypick my state before I pass it to a component as props.
I think that's a good exercise: to try and build an application thinking of it as a series of actions on state first --and then how that may play onto UI-- to get to appreciate functional components. I'm curious to know why you think why you think Redux only "pretends" they aren't though. (:
Also, conceptually, you often have a lot of state that's very directly concerned with and specific to the UI, and isn't just idyllic, agnostic "data". Things like "is this menu open or closed?" and "what's the current string value of this input (which isn't meaningful until the form is submitted)?" In Flux, those things tend to add a ton of boilerplate in terms of change actions, and split tightly-related concerns into separate corners of the codebase (if I remove this menu component I have to remove its open/closed state variable and the corresponding action).
To be sure, there's not really a great way to decouple things in the reactive architecture. I personally lean towards stateful components that are decoupled at their boundaries instead, which does carry its own downsides. The only solution I've ever seen that truly felt right was two-way databinding, which Vue (sort of) still has, but which has fallen out of fashion in general because it requires "magic" and because it tends to come with performance costs.
The entire UI is specific to the UI. Trying to separate "entities" or "server data" from "UI concerns" is IMO a waste of time and just confusing.
At the end of the day, you have a state tree, and you project it to a UI. Where that data comes from and what it represents doesn't really matter. Events in the UI generate an log that can get folded into new state to then be projected again. These events could be generated by a button being clicked, or an XHR request completing, but that doesn't change the nature of the payload.
One important thing though, in most of these models, the state shouldn't be "is this menu open or closed". It should be "Is the user focused on an arbitrary task or not". The menu being open or closed is a projection of that. This way when your designer comes and says "No, this thing shouldn't be a dropdown menu anymore, it should be a modal", you don't feel the need to rename your arbitraryMenuOpen: true state key to arbitraryModalOpen: true instead. Saves a lot of time.
Elm is a pretty good example of how all of this works. Its fairly different from Redux and co (even though it inspired it a lot), but its interesting to see how all of these things absolutely can work. They get messy when retrofit into React and JavaScript, but it's not an issue with the concept, just the implementation.
Wait, they don't though. That's the whole point of functional components. They are of the form:
const Component = (props) => <JSX />
Where are said "literally passed" actions here?> So there's bi-directional coupling between the UI code and the Store (the UI code renders from the state, and passes messages back to the store).
This isn't bi-directional binding. state determining UI, UI sending queued actions and actions determining state is one-way data flow. Bi-directional coupling would be tying a reference in the state to a UI element.
> Also, conceptually, you often have a lot of state that's very directly concerned with and specific to the UI, and isn't just idyllic, agnostic "data". Things like "is this menu open or closed?" and "what's the current string value of this input (which isn't meaningful until the form is submitted)?"
This is architectural, and is why components have their own state. Its up to you wether you want to keep this as application state or local volatile state.
> In Flux, those things tend to add a ton of boilerplate in terms of change actions, and split tightly-related concerns into separate corners of the codebase (if I remove this menu component I have to remove its open/closed state variable and the corresponding action).
Which is why I don't put it in the main application state (:
> To be sure, there's not really a great way to decouple things in the reactive architecture.
I mean, not if you're dumping everything on your application state, no.
> I personally lean towards stateful components that are decoupled at their boundaries instead, which does carry its own downsides.
Curious to learn what you mean by "decoupled at their boundaries". You mean components that are de-coupled from each other? You can make re-usable, functional or stateful components that are de-coupled from application state.
I think the main takeaway here is that not all state is the same, there's state that's part of your core application logic and state the component needs for its display only. Treating them as the same thing does limit the re-usability of your code and make dealing with your application state tedious.
> The only solution I've ever seen that truly felt right was two-way databinding, which Vue (sort of) still has...
There's other solutions (: I don't think Netflix, Facebook or AirBnB have all the state of their menus tied up with the state of their user data and and have all components be use-once because of that. Good state management can make things scale, and functional components very useful!
> but which has fallen out of fashion in general because it requires "magic" and because it tends to come with performance costs.
Yup. It's also hard to know where or how certain state is changing. It definitely allows you to build small applications very quickly, but it doesn't scale all that well.
The author is wrong. Vue doesn't have two-way binding. It has one-way binding with events. Components can't force anything upon their parent's state with an event.
> "You can use the v-model directive to create two-way data bindings on form input and textarea elements. It automatically picks the correct way to update the element based on the input type. Although a bit magical, v-model is essentially syntax sugar for updating data on user input events, plus special care for some edge cases."
I'm not knowledgeable enough on the matter to say if this is or isn't, and to compare vs Angular, etc. But don't blame the author for this one ¯\_(ツ)_/¯
All props form a one-way-down binding between
the child property and the parent one: when the
parent property updates, it will flow down to
the child, but not the other way around. This
prevents child components from accidentally
mutating the parent’s state, which can make
your app’s data flow harder to understand.
https://vuejs.org/v2/guide/components-props.html#One-Way-Dat... AngularJS uses two-way binding between scopes,
while Vue enforces a one-way data flow between
components. This makes the flow of data easier
to reason about in non-trivial applications.
https://vuejs.org/v2/guide/comparison.html#Data-binding <Component v-model="foo">
is basically shorthand for <Component :value="foo" @input="foo=$event">
In particular, the child can't affect the value of the parent's "foo" attribute except by sending an event. This is in contrast to Angular 1 where changing "foo" in the child would also change it in the parent, which would often lead to confusing data flow cycles.As other people mentioned, Vue indeed doesn't have two-way binding, and v-model doesn't have the pitfalls that Angular had. It is just syntax sugar.
Maybe it's about time Vue people remove the mention of two-way binding from their websites, since it is being used to attack the framework. I've seen that in other discussions here in Hacker News.
https://reactjs.org/docs/components-and-props.html
The best thing to do is just to brush up on functional concepts, thinking about things in terms of composition and application, and threading state through your application and flowing back through to the top via dispatches. Learn more about flow (the concept, not the framework). I like to picture a waterfall, where the water is state that always keeps flowing no matter what it hits. State should start at the top from some source, we don't care what that is, and then flow through the application down into the leaves. Functions can do transforms and reductions on state, but they should never hold on to state the way class components do.
In the last SPA I wrote there's about 100 components, less than 5 of them are stateful.