343 points · by danabramov · 7y ago · 151 comments
However, the entire mentality of the community is moving towards having behavior tied to specific portions of the tree; in essence it's common-practice to have stateful components. With Hooks this is even more the case.
Instead, the nature of UIs is that changing something in a part of a UI might and will effect something in a completely different location: when I click the button, open a dialog, show a spinner and reset the user profile screen.
The problem with writing stateful components is that the behavior (such as the one above) is tied to the UI representation (at which level of the tree should I write this logic so that it effects all the aforementioned components?).
We are essentially going back to tying logic and representation; something that we've been trying to avoid over the past decade or so.
I'm not saying React doesn't allow you to do differently; things like global-state (Redux, MobX, etc.) allow you to separate behavior and representation quite well. I'm more confused about the recent lack of best-practices surrounding this idea of separating logic-and-UI, and instead they're pushing towards: "Yeah now with Hooks you can even more easily bundle logic-and-UI together and have them tightly coupled". Which to me seems really confusing.
Among other wonderful features, Fulcro has built-in support for state machines [2].
[1]: https://github.com/fulcrologic/fulcro
[2]: https://github.com/fulcrologic/fulcro-incubator/blob/develop...
We are going to be incorporating xstate at a basic level in one of our next projects, but I’d eventually like to see it become entrenched in how we do all UI development.
Doing it in a way that best utilizes the strengths of both of those abstractions will happen eventually, but old habits die hard. As evidence look at all the convoluted ways people try to make all style information public, conflating the public aspects and implementation details.
There is just a ton of sloppy thinking and very little design pattern leadership. For example Airbnb used react for a long time and all it really gave back to the community was an extremely anal set of linting rules which incidentally differ from Facebook’s in annoying, nit picky ways.
One can imagine the amount of bike shedding that such minutiae creates across the entire react community.
A bit like a decade ago and earlier when we still used server-side rendering:
request parameters + backend state = some html
But I believe the GP is referring to interactive UIs, not static HTML. For example, you would never have a date picker widget render each month's calendar using a full server-side page refresh.
- either you're coupling the logic and the representation.
- or you have coupling between your different UI components and the global application.
You're talking about the first kind of coupling and say it's bad, but IMHO the second kind is even worse in some cases.
There is no silver bullet, it's all about tradeoffs.
But I think we are learning learned that complex state is graph shaped. There aren't any good answers here. You need a real graph "database" in the UI
I think it also shines light on why GraphQL has proven to be such a great fit for UI programming, more so, I feel, than inherently tree-oriented solutions to state management like Redux.
This quote from a blog post from the Apollo folks really internalized the essence of GraphQL for me:
"GraphQL allows us to extract trees from the app data graph."
https://blog.apollographql.com/the-concepts-of-graphql-bc68b...
Highly recommend taking a look at the article if you're interested at all in GraphQL. I think the first few sections at least serve as a great primer, though later sections go into Apollo specific implementation details that might not be as interesting for a newcomer.
The apples to apples comparison to Redux here would be approaches like Apollo's apollo-link-state and Relay's client schema extensions that allow you to manage local state with GraphQL (in addition to server state).
Although Redux also allows you to store state in a purely normalized form that's more amenable to graph traversal, and the prevailing wisdom in the community says that is the de-facto approach for managing state in complex apps, Redux certainly doesn't enforce it or make it effortless and foolproof. That is in contrast to most GraphQL based solutions where normalized state stores are the default, and you have to work to deviate from it.
In essence, with GraphQL-based solutions, you conceptualize your data as a graph, extracting trees out of it to use in your UI (which is fundamentally a tree) through queries/fragments. That Apollo/Relay stores the data in a normalized tree by default is an implementation detail that you normally wouldn't have to worry about (in fact there are alternative implementations of the Apollo cache that stores data in graph form to enable a different set of performance tradeoffs: https://github.com/convoyinc/apollo-cache-hermes). Whereas with Redux, that implementation detail is the user's responsibility, i.e. you have to manually implement the transformation of your data graph into tree form, normalized or not.
Soon however, I realized that in practice (at least in the context of a React-based application), there's little to be gained by storing state that is truly temporal/localized in a persistent/global store (which is necessary for enabling a truly pure mapping of state to UI), and that there's in fact much to lose, because:
1) By nature of being temporal, they're state that needs to be initialized when they need to be used and destroyed afterwards, otherwise we risk exposing stale state to the next usage in time.
The initialization/destruction process often needs to be synchronized with some lifecycle of a component. Animations on mount/unmount, and form input that needs to reset when closing a modal, etc, are great examples of this.
If we used component local state to begin with, that state lives and dies with the appropriate component automatically, with no additional ceremony.
On the other hand, if we were to store that temporal state in a persistent state store, we'd still end up having to create components that hook into component lifecycles to create/destroy that state at the appropriate time in the persistent store manually, which, even if we ignore that it's often a tedious, error prone process, means introducing impure components into our tree of pure components anyways, so we've really gained nothing over the component local state approach.
Not to mention that temporal state is often frequently updated (as an example of an extreme, FLIP animations (https://css-tricks.com/animating-layouts-with-the-flip-techn...) by nature require at least 60 state updates per second), and having a few of these in a persistent state store can wreak absolute havoc on application performance if we mess up even a little bit in our pure rendering optimizations, which is notoriously tricky to get right perfectly due to all the edge cases we have to be mindful of (not creating new event handlers functions with every render is especially tricky in a codebase that's committed to using only "pure" components; in fact, I'm not sure if that's even possible in the strictest definition, since all the techniques I've worked with involve creating an impure class component to memoize the function, and the new useCallback hook likely isn't pure in the strictest sense either).
2) By nature of being localized, they're state that no other component should ever be concerned with.
Making them accessible at all to other components, as we do by storing it in a global state store, is by definition a leak of implementation detail, which over the long term makes it harder to change the components that use localized state, because we have no easy way to guarantee its "localized" state isn't being depended on by something else. In fact, to suggest that they're using "localized" state at all at this point is more wishful thinking than anything else, because nothing exists to enforce this localization once we put it in the global store.
At best they're just extra noise we need to ignore/filter out when debugging/serializing the state of the store, and at their worst they can lead to extremely brittle and over-entangled component trees where changing one part of the tree can inexplicably break seemingly unrelated parts.
On the other hand, component local state is for all intents and purposes, truly localized. We cannot access component local state outside of the component itself unless we explicitly expose it to children as props or to parents by refactoring it up a few levels, at which point we're making the explicit decision to change the locality of that state to include more/different components, and that decision is completely self-evident.
Whenever we decide to use component local state, we can rest assured knowing that their locality is enforced by the React runtime, rather than some handwavy global store access convention that we'd otherwise have to resort to if we stored localized state in a global store, which involves an ongoing cost in terms of enforcement while offering little in the way of real safety.
To be perfectly honest, some/all of the points I mentioned could potentially be attributed to React not abstracting us far enough away from the stateful nature of the underlying platforms it builds upon (the DOM for web, native UI platforms for React Native). For the case of temporal state, I can imagine for instance a potential alternative/higher-level library where React's stateful lifecycle hooks are replaced with some elegant purely functional primitive for supporting the same use cases, perhaps something that models _time_ explicitly as part of state, like Datomic does with transactions (nothing similar comes to mind for handling localized state though, so perhaps encapsulation and true purity are just at odds on a fundamental level).
Though I have not yet seen anything that would enable a truly pure state -> UI mapping for building non-trivial applications while avoiding the aforementioned drawbacks, I'd of course happily re-evaluate my position on the feasibility of this approach when I encounter such a solution.
Perhaps, I mis-understood, but when I do .setState({data}, fnToCallAfter)
as a user of React, I do not really know where the state is stored, in other words, I do not store in global/persistent store.
---
I do use React.Context quite a bit to store my LoginState, my special purpose in memory store (using Immutable.js) that acts as cache for some often used/expensive to get backend data. When my LoginData, or CacheData get updated, react automagically calls 'render' (and static friends) on all the mounted components that have signed up to observers to the Context's changes.
This is very similar to newly release AndroidX jetpack Lifecycle-aware ViewModel, that calls the observer methods, only on activites/fragments whose lifecycle is 'active' (this reduces complexity of managing android activities during the 'rotation/config' changes.
---
I am just not clear where you run into a situation where you had to use the component-level state management in react, that required you to see the innerworkings (or implement) your mechanism to store component's state.
It turns out it is a lot easier to program dynamic 3D scenes using this method, rather than trying to do two-way binding like Angular, JQuery, etc do. And the performance is typically better too. Imagine trying to do two-way binding in a AAA game with 1,000s or even 100,000s of individual objects in a scene. It would be a programming nightmare! Instead much of the effort is spent trying to reduce the amount work the GPU has to do when rendering the entire scene such as occlusion culling, distance-based level of detail, etc. React's virtual DOM renderer is also trying to render the scene (DOM) as efficiently as possible. But admittedly it is much simpler than Unreal Engine's renderer, but the high-level concept is similar.
I think this is why React feels so natural to so many people when building dynamic web UIs compared to JQuery, Angular, and even Vue.
React has certain weaknesses that aren’t seen in other UI libraries/frameworks as well - forms are a complete mess to work with, even with formik, and animations are pretty problematic.
As with anything, there are tradeoffs to approaches. FB isn’t as form heavy in general, so optimizing how it works for the rendering inputs from external sources & dev usability makes sense for their use cases. It’s important not to conflate this by overpraising.
Could you elaborate on this? I've been creating form heavy react apps for a couple of years now and haven't really come across anything that would make it 'a mess'.
There is another component to React which I didn't mention that gets inspiration from the 3D world: the API. When I first saw React's API, the first thing I thought was "that looks kinda like OpenSceneGraph, cool!" Now this is the very subjective part, having spent 8-9 years doing 3D graphics React felt natural to me. Given its popularity, I must not be the only one either. I am glad you like the Vue API but it doesn't feel like a 3D engine. For whatever reason, many people seem to prefer the 3D engine feel. On purely technical merits, I think React and Vue are basically the same. But I think there is some intangible difference in how the tools feel. Some people like React and some like Vue and both are right. However more people seem to like React.
React on the other hand tries as hard as possible to avoid rendering, in fact it's whole design of immutability isn't because functional style is better, it's just convenient for it's requirements to avoid rendering.
For me react is more of an antichrist of UI tech, as much as I use it and rely on it, the day I can just mutate some state and that renders (i.e. .. just straight up dom), the better.. if I want to then layer on some immutability patterns then that's entirely in my apps domain.
3d engines often go to great lengths to avoid sending unnessesary data to the GPU. Frustum culling or more sophisticated occlusion culling are standard practices.
React feels more like "retained mode rendering engines" which were popular in the 90's and early 2000's.
Diffing and piecemeal updates are an implementation detail/optimization.
Even before react, I had webapps where I'd cobbled together helper objects that did things pretty similar to react, although obviously not as robust.
I've been doing GUI apps for long enough to have seen a few attempts in a variety of IDEs (and languages). I like React exactly for this reason - that it models what they've done with components, but in a way that is more robust and flexible. IDEs tend to come and go but JSX as a language seems to have grown beyond React. It's a relatively good way of describing UI that can be read and understood while leaving ample space for dynamic composability which has historically been an issue to represent in the IDE UI builders I've used. I've usually had to resort to mixing UI builders and own code, or giving up on the UI builder entirely and instantiate classes myself.
I like React because of the trade-offs. It's not perfect. It's just imperfect in some acceptable ways.
And Desktop UI libraries tend to be even more complex. And as usual, warts are on the outside.
https://www.bitquabit.com/post/the-more-things-change/
Prior discussion: https://news.ycombinator.com/item?id=10381015
Certainly when I first saw it my thought was, "hey someone did Cocoa for the Browser, nice".
https://blog.metaobject.com/2018/12/uis-are-not-pure-functio...
"One way data flow" is pretty much exactly how MVC works, except that MVC decouples a bit more: the model is only allowed to send #changed notifications, the view then pulls what it needs. The data still only flows in one direction.
"Actions" in Redux are very much the "Command" pattern as used in C++ GUI frameworks such as PowerPlant.
I mean, for a start, no 2 MVC frameworks actually agree on how to pass data around.
React is just the V.
React is just one of paradigms. And UI is a multi-paradigm entity. When architecture of one component can benefit from React model, others - may not.
Consider basic <input> as a component. In order to update its value you just need to execute this:
input.value = "New value";
Wrapping such input into React.Component is a waste of resources.As for me Twitter's Flight ( https://flightjs.github.io/ ) is less constraining - more general if you wish.
It is just very simple infrastructure around PubSub idea. Loosely coupled components interact with each other by posting UI lifecycle events. Components subscribe themselves to such events and react on them in most optimal, component specific way.
Some of components may use React internally, some have better means to update themselves.
Apollo is also nice. It's best for display heavy apps as documentation and typechecking is at least enforced/built-in. But I feel it's too abstracted/magic for heavy state apps. I still need to find good flow with Typescript and Apollo though. (to not repeat types - haven't tried yet really).
Redux IMO is overkill and is/was abused. It's good if you want to store some global data/config and have clear view od it. But for very dynamic state MobX is much less overhead.
I would just like a good way to share components and simpler styling.
BTW for simplest state management I like pure class implementation and just calling update on main component after event handler finishes. It's easier to test and good enough for simple UIs.
Shadow DOM and custom tags make it possible to closely mimic the way we used to do UI development back in the Delphi/VB6 era. I like how eg. css properties only apply to a given component.
Polymer seemed like the most lightweight possible way to implement this because it uses the browser facilities. I understand that React also has components and custom tags (JSX) but it doesn't use browser facilities but rather implements them itself, which just sounds like the wrong way of approaching the problem.
- Write codes in ES6/7 or TypeScript (transpiling using babel).
So the syntax is exactly like what you're writing on the web (not React-like syntax)
- Bundling using webpack (with a sensible default, zero-configuration FTW)
- Use any front-end library (redux, lodash, rxjs, redux-observable etc.)
- Supports Hot Module Reloading (sub-second reloading)
- Supports react-devtools & redux-devtools (Time Travel Debugging possible)
- Super easy to test & debug in multiple platforms
The problem we're facing now is that it required both React & QML knowledge. In the new version, I'm working on completely new APIs to support developing desktop application using only React. Would love to hear your opinions on this approach.[1]: https://github.com/longseespace/react-qml/tree/next/packages...
This project looks really interesting, definitely something I'll be following.
Do you have any plans to expand on documentation a bit more? At present your HN comment tells me more than the README does.
https://reactjs.org/docs/hooks-faq.html#what-is-the-prior-ar...
So in a nutshell: "React as a UI runtime" considers React as implementing part of your UI's execution model. In other words: instead of your code having to call appendChild, setAttribute, etc. to modify the UI, React does that.
A ) Dependency Tree (eg dom or virtual dom) is the interface user interacts with.
B ) Each interactable element in the tree can have its own state.
C ) Each interactable element gets data or update data from/to its own state.
It can also get data from 'properties' that a parent passed on (but the interactable cannot update those properties itself, instead it must call its parent's function to do that)
D ) After the above A, B, C are setup -- the code interacts with the state, not with UI elements
E) The UI runtime is a collection of mechanism that supports A, B, C.
This includes :
1) Primitives allowing Interactable to be attached and interact with the dependency tree, ability to receive data from parents
2) Well defined (from both APIs, callbacks, and Data) primitives -- that enable state management within the Interactable, and across their dependency tree
This also includes mechanism deciding efficiently, which state changes affect which Interactable)
3) Developer friendly run time helpers to debug and manage the above
----
Cleary A) --> can be a dependency tree of Excel cells, or Matrices, or robot's extremities, for that matter.
Clearly B) (the state) is widely appreciated these day ViewModel (as it is called in Android's new JetPack LiveData components)
The state is also the thing that can be validated, even with TLA+ (which is what am thinking about, in a downtime).
And it is much much easier, in my view to map interaction business rules to state, rather than to UI.
---
I am looking forward to try this with my console UIs project.
---
I also have a strange feeling, that this model will work when I have to manage complex backend interdependencies,
where updates to distributed caches affect the algorithms running across a server farm.
---
Ok, now that author feels better, let's move on..? Or what is the purpose of such 'disclaimers' and 'warnings'? Let the reader see whether the article is at their appropriate level, don't patronize...
I really dislike these. I can skim the text, and within 30s, I can see whether it might be my level or not. This feels, however, that the author is purposely driving me away for no other reason than 'you don't make a living with react, so shoo, this is for the big boys'.
I think this is reasonable for this author to want to emphasize. It's quite common for a beginner to make one of several reasoning mistakes that might push them away from trying something or push them away from something they were already using. The beginner who hasn't used a thing yet might think 'I need to understand how this thing works in detail before I can use it' in which case they might think reading an article like this is an appropriate way to get started. The beginner who has already started using a thing might think 'here is a good article about how the thing I've been using works in detail which I can't understand -- therefore this thing I've been using must be too hard for me to use and I should look for something else'.
I assume for popularity retention reasons, the author doesn't want to encourage either of these kinds of mistakes.
I did feel that the yellow warning sign was a bit much. There was also a line about it not being for designers. As somebody with both design and engineering backgrounds, I felt less enthusiastic right away — mostly because I dislike buckets being enforced. It encourages people to put themselves into one over the long run, which in turn has a tendency to stunt their progress. It’s also odd when any educational resource (higher ed in the US being a great example) introduces itself by trying to be inaccessible. It feels counter to the professed goal of the institution / article.
Anyways, I guess I felt the comment above is a valid thing to discuss if it could improve other people’s efforts to write similar pieces.
As an aside: ironically, the article is fascinating from a design perspective. Just not the particular bucket of design the author was thinking of when he wrote that line.
Another unintended effect can be contributing to the perception that React is only for people with a strong programming background rather than, say, a11y expertise. I don’t want that either and that’s why I mentioned there are multiple ways to look at React.
Yet another problem is that random things from my posts are sometimes used in interview questions. :-/
I trust a curious reader to ignore the disclaimers and dive in anyway.
But I also wish I didn’t need to put it there and I emptathize with your frustration.
Do you think that without the warning, a beginner would deep into the article, and 50 minutes in, he/she would be like 'heeeey, wait a minute! This is not for me! Why didn't he tell me?'
If not, then such a disclaimer is meaningless.
I really don't understand your issue here.
Your complaint about it makes it look like you believe the post was written for you personally, with no regard for the wider audience. That's idiotic.
How do I know? Because I have disclaimers here and there that are obvious for most people and still help to reduce the support burden.
Of course, he didn’t consider the massive inconvenience he was causing to god level programmers like you when writing his disclaimer. Shame on him!!!
To tell people what to expect going in, so they don't have to lose their time if they're just starting out and looking for a quick high level tutorial etc.
Why should Electron users have all the fun?
Some Ux in regedit?
Run dialog not permitting ctrl-arrows?
Really, we need to wake up and realise the fact that the ui experience in windows is not good enough at all.