131 points · by hazdiego · 7y ago · 80 comments
Every single time somethings come up, in the JS word, they try to repeat one of the mistakes from the past and completly ignore everyone else solutions and experience. It's like a compulsion.
In a year or two, your dependancies will be a representative sample of all permutations of those solutions, and will have to be maintained in that state forever, incompatible, or abandonned. You'll open some of them, trying to fix it, but you'll notice they all use different coding style, best practices, libs, and tooling. The dev that fought you in comments saying it would be fine is nowhere to be found now.
Most JS devs don't care. They don't maintain their stuff. Appart from the stuff that get famous because made by great coders (no matter the language), most projects die silently. There is a terrible graveyard hidden behind the corporate wall. Java, C++, Python and even Ruby projects are standing well and alive, next to the countless bodies of the last generation of JS frankeinstein monsters that were hype-sold to upper management to create something that could have been done in PHP 3.
Then a new stuff will arrive in the JS space, with again the potential of creating more confusion, more technical debt. You will raise your voice, and the JS community will scream back at you that you don't know what's good, you want to live with cavemen, and everything is great. They will get angry, and never see any problem.
Then rince and repeat.
For unknown reasons most front-end developers don't wanna hear that and love to start with mega complexity and boilerplate where just a simple flux store or a library like 'unstated' would suffice. Anything leaner than redux is very welcome for the average companies web app imao.
It tooks years to sort that out.
Yes except we spent years having so many projects crashing under the complexity of using a store, most juniors being unable to produce decent code and managing the numerous layers of indirection.
Yes except we learned later, hey, a store is not required for most projects. You totally should use react without a store for your little service. But we won't give you a best practice to do so.
Yes except for a single little incremental counter in redux, tutorials invite your to create a store, an action factory, and action dispatcher, an adapter to connect them, and then use a provider to pass the store. To escape this madness, you may use, yet another abstraction du jour, or just write hundreds of lines of boiler plate. Or do it another way, hoping it's alright, and creating yet another differently styled code base.
Yes except mobx or vue are way easier to use. Oh but they are yet another tool to learn and manage.
I agree with the sentiment so just out of curiosity: what are these existing solutions that people should look at and take lessons from?
- Clear best pratices provided with tools. Do you know how to code a react project ? The person next to you has a different answer.
- Reference implementations. We heard about the Flux pattern and the idea of stores for a long time before understanding concretly what it meant. And then pouf, 200 store and routing implementations differing in opinion, and no voice or advice about what to use and how.
- Integrations layers. Everything is a lib gets old really fast. And "look how redux is simple" as well. Assembly is simple but I don't code my website with it.
- Deprecation policies and clear migration path. Webpack was weird, quirky and badly documented. But the worst thing was that once you figured out something that works, a new version broke compat.
- Avoid dependancy creep. When a dependancy has more package metadata than code, there is a problem.
- Don't encourage a cowboy culture. It's great anybody can start coding in JS in an afternoon. It's not great that after a month the same person market his lib like it's the best thing ever and production ready.
- Documentation that makes sense. People explaining a new tool by showing you something webpack based or in in jsfiddle is not doing his job properly.
- Api best practices and design patterns have existed for a long time. Use them. KISS. DRY. Don't break user land. Principle of least surprise.
- Don't rename things that have had conventional names for decades. "Flux is a not MVC" is a lie. It's mono-directional, it encourages single instance immutable model. But it's still MVC. Most people looked for very complicated answer to what is flux because of that. And who name a lifecycle method "componentWillUpdate()" ? "onUpdate()" and "onPostUpdate()" are the legacy jargon. And then "UNSAFE_componentWillUpdate()" ? Really ? Like really ? Never heard of warnings ? Using the JS className instead of the HTML class in JSX is also still amazing me, not in a good way.
- Don't give the same name to 2 different products. Looking at you angular. Also SemVer is not a bad word, I and don't want your weird release name. That double the suff I potentially could google for.
- Conventions are nice. They should not replace configuration, but they complement it very well.
- There is such a thing as a "typical use case" for many tools. You should design for that, and if it's not possible for you, build a layer of top for that. Building facebook is not "a typical use case". Passing data from a children to a parent after a click and a preventDefault is. Why is the later so damn verbose ? Why did have I to google it ?
- Scaling down is as important as scaling up. Make simple things easy and complicated things possible, not the contrary.
- New is not always better, sorry barney stinson. Satisfying users with working software is. If you make or use something new, you should evaluate the cost for you and others before going "oh shiny !".
There are many others, but I don't feel happy writting this, so I'm going to stop.
Nice idea and examples! Let me know if I'm wrong, but the main difference between `createContainer` and a `React.createContext` call is that you memoize inputs, correct?
The way this interacts with Hooks to enable state sharing is pretty cool. Hopefully someone builds a complete i18n lib on top of something like this.
I stumbled across it earlier this week and it's a joy to use so far. The api is inspired by clojure atoms, and typescript inference works great out of the box.
But asynchronous effects! And their orchestration with powerful tools such as generators or observables! Isn't it worth a dependency or three?
See my post "The History and Implementation of React-Redux" for more details:
https://blog.isquaredsoftware.com/2018/11/react-redux-histor...
https://github.com/diegohaz/constate/blob/master/src/index.t...
Wait until you start seeing components that depends on various trivial libraries (hook functions) for state management. My bet is on setInterval to be a very common one.
1:https://overreacted.io/making-setinterval-declarative-with-r...
It really feels like if there was some way to put this really dirt-simple counter code into a plain-Jane Javascript object then a lot of this hand-wringing about state management in React goes away (contexts are an interesting little solution to things though)
What I tell my students is that you want to think of your app in three layers -- the data layer (Redux/data fetching), the glue layer (@connected components, useEffect hooks), and the presentational layer. The representational layer should be just your rendering logic and the data layer should deal with fetching/storing/updating data. The two should never interface directly, only through your container "glue" components.
I do think you can have a hook return a javascript object though for the normal reasons of encapsulation and such.
export function counterView (count) {
return <span>{ count }</span>
}
export function Counter () {
const [count, setCount] = useState(0)
// … useEffect to setInterval count or whatever
return counterView(count)
}
At this point, though the question becomes is this pattern buying you anything? Pure view functions should be easier to test, but React testing library's act() tool looks like it isn't that much more painful to just test the full component. Similarly, pure view functions are potentially easier to reuse with different "component logic", but I'm unsure how often that would be the case.It's maybe a bit clearer as a pattern where the "stateful" and "stateless" stuff may be than mixing the two, and certainly seems like it might help make it easier to follow the "Hook rules" (most of your loops and conditionals should be inside the "pure" function). But it's potentially also just a source for extra noise/boilerplate.
Like I said, I'm still thinking about it, and something I expect to explore in an actual codebase at some point.
That being said, I don't agree that hooks are futile, because, using hooks, your state logic can be reused. For example, if your app uses 10 independent counters (with different render logic and different styling), hooks are definitely useful to reuse the state logic.
Unstated has state containers as separate entities. This one is about seamlessly switching from a local useState hook to a context-based one with minimal code changes.
I’m not convinced it’s worth the hassle vs just creating your own contexts though. Here is the full source: https://github.com/diegohaz/constate/blob/master/src/index.t...
This is what I was thinking when running through the source. The problem to solve, I think, is to get rid of the providers. Or rather, make it less jsxy. For application-level contexts, you can easily have 10+ providers at the root of the application. You could make them HOCs, but that's still super ugly. Hooks made the consumer side a lot cleaner, now it's time to do something about the provider.
The mapStoP and mapDtoP are just plain functions that do what they say on the tin. Easy to read/write once you understand the pattern.
The connect HOC like all HOCs is a bit of a smell, but easy enough to use without understanding much about HOCs.
Likely soon hook replacements for connect will make all that "verbosity" even simpler and easier to work with.
For instance, useMapState and useActionCreators from this proposal for redux hooks: https://github.com/epeli/redux-hooks
That is problematic because configurations are settings not decisions, which means you need work arounds for edge cases and work arounds for the work arounds. If instead you treat everything as a requirement instead of anything as an edge case then you are forced to make decisions and write the corresponding code. New requirements may necessitate refactoring of current decisions down the road, but the code stays clean, small, and deliberate.
At the most simple you only need three things: a central consolidated point of settings (object), storage (localStorage), and interactions isolated to their respective purpose (handlers).
I have explored this space from nearly every angle. I've tried a multitude of languages and technologies, and there is no place where this has been solved completely and there are always drawbacks to any solution. But that doesn't mean those solutions just exist because their authors were bored. They exist because they actually solve a problem.
I would very much like to see you write a large react application using only the concepts you mentioned. How are you going to deal with side effects? You realize you can't just fire those off willy nilly, right? How are you going to pass information upwards or across the component hierarchy? Callbacks? Have fun with writing that and reasoning about it afterwards.
People love to bash on the JavaScript ecosystem and rarely do I see anyone praising it as it deserves. There are some incredibly ingenious solutions and architectures that have been invented in that space, and anyone who isn't just a troll trying to fit in with the other cool kids and has actually tried to write a complicated frontend application today appreciates the hard work that is happening there, and understands why new solutions keep being invented.
I have been writing code for more than 20 years and writing JavaScript for more than 11 years full time. The UI, accessibility included, is not the challenge. I have been doing this long enough at enough employers to watch people fail the same ways over and over and consistently qualify bad decisions with the same repeated excuses.
> This is such a gross oversimplification of the problem
It is not an oversimplification if proven in practice more than once.
> rarely do I see anyone praising it as it deserves
I love JavaScript/TypeScript. Some of the complaints against JS are absolutely justified and some aren't. The unjustified complaints are typically from insecure developers of other languages that loathe the completely foreign expressiveness and flexibility allowed by JS. The mountains of code some developers require to perform trivial tasks is absolutely worthy of ridicule though.