by BiteCode_dev · 5y ago · 0 comments
But it's not "the best things to happen to react". It added plenty of complexity to the system.
Hooks have been embraced by the community in a way that now many features only exist as hooks, which makes ones life difficult as soon as you don't want to use a functional component.
An no, not everything should be a functional component.
In fact, some things are really hard to do with hooks. I dare you to craft a simple reusable _and correct_ useInterval() hook without stealing the solution online.
Go on, I'll wait.
function useInterval(cb, ms, deps) {
useEffect(() => {
const id = setInterval(cb, ms)
return () => cancelInterval(id)
}, [ms, …deps])
}
I think this is much nicer than having interval maintenance and prop diffing is didMount, didUpdate, and willUnmount. Certainly it’s easier to get the hooks right (for me) and all the logic ends up in contiguous lines of code. It’s a higher level interface so it takes a bit more practice to apply - feels like Ocaml more than Java.Dan Abramov has a good post that explains the issue here well: https://overreacted.io/making-setinterval-declarative-with-r...
That's the whole problem with hooks: when things are easy, they are nice. When things are complicated, unfortunately, they look easy, and you start to think you understand what's going on. But most people, me included, don't.
I've seen people reimplement it wrong in my codebase more than once, whereas no one gets useInterval incorrect because.. we can actually share that functionality across components now.
Why do react guys choose to fight these battles in the first place? We had a clear model, MVC (not web 1.0 mvc which left MC at the server-side, I mean fully-in-app one). All these setups and teardowns were done in “C” part, which didn’t depend on how exactly views are [re]arranged on the screen. And all interactions went through C, leaving little to no state in V (only very local ones, e.g. whether a combobox shows a popup currently, or is there a div-tooltip above a label). Then react broke in and told us that all we have is views/components and got a grip on their lifetimes, forcing us to jump through these hoops.
And that functional-async thing was not even the reason for that. React could have the same “off-screen” controllers with explicit lifetimes and setState() and friends, to be more testable and composable and all of that. But they chose to push all state to transient objects and then began to heroically solve the mess created by themselves in the first place.
My current company, for example, enforces a pretty strict architecture where core application state lives "outside" of React [0]. What page we're on in our SPA, for example, is determined by state in our page store. We don't explicitly rely on component mounts to fetch data - instead, when we switch to a certain page via some action (like OpenUserPage), and _that_ fetches the data needed for that page. When we navigate away from the page, we call CloseUserPage, which unloads that data.
We try to push all business logic into discrete use case based actions. Like you mention, we use local component state strictly for view state (e.g. is this menu open?). We try to use hooks like useInterval sparingly (I think we only use it for things like updating relative timestamps every minute). We do use setInterval in business logic though, where it's simpler to reason about, for stuff like polling.
In an ideal world, there'd be very little need for complex hooks, where most components are strictly function components that only re-render when state that they're subscribed to in the store changes. But the real world is messier, and making a beautiful SPA with animations and whatnot often requires tricky view state logic with hooks. And of course, you have to be careful to not re-render components unnecessarily in performance critical situations where you're rendering a lot of stuff.
But I think the sort of high level separation you're describing can and does exist, and IMO striving for that separation makes it much easier to understand how data flows through the app, and obviates the need of digging into component lifecycles to manage the state of the app.
[0] At the end of the day, it does live in a top level context, but we don't interact with that context directly from child components.
you have to be careful to not re-render components unnecessarily in performance critical situations where you're rendering a lot of stuff
Interestingly mithril’s author, the library that I use in place of react, suggested that for humongous doms it’s better to split it into sub-apps. In short, you make a shallow component that mounts another entire “app” into its div on its mount, so that updates do not propagate downwards (the main app simply doesn’t know about subapps). Otoh, events propagate as expected due to regular dom. Personally I find mithril’s approach more outside-state compatible, if you don’t do funny tricks with event bubbling. If you’re not familiar with it, it’s the same hyperscript/vdom, but re-render()s everything after any event related to dom it controls, unless you tell it not to in a handler. That is fully out-of-your-way approach compatible with anything. Animations, jquery components, you name it. I don’t get why people choose react, which seems to be the opposite of that. What do you think I’m missing here?
And thanks for your time and the expanded reply!
Edit: frankly, I wouldn’t even bother with react and would just use what fits, but its presence is overwhelming in a sense of both community and job options. If there is a way to use it without abstraction pain, I’d like to understand it.
- lifecycle methods are clearly named and explicit. Hook lifecycle is implicit and you better have the whole doc in your head. It depends on this weird array, and have a few edge cases.
- you need useRef() to hold the interval ID for it to work with hooks. A fact you are unlikely to realize without a hard debugging session. While a simple attribute will suffice with a class.
- spreading accross methods is actually nice: people intertwine code for various steps easily in hooks, making a mess of things
The benefit of the hook version, of course, that the reusable version is very nice.
> Hook lifecycle is implicit and you better have the whole doc in your head. It depends on this weird array, and have a few edge cases.
useEffect() will run after each render if you don't specify a dependency array. Otherwise, it will run only if any dependency in the array has === changed. That's pretty explicit to me (but I think you mean in terms of naming.. but I think one or two reads through the docs should make it explicit).
The return "cleanup" function is a bit odd at first, sure, but it's really just a function that will run _before_ the next effect runs.
The general recommendation is to not use the dependencies array at all unless necessary.
> you need useRef() to hold the interval ID for it to work with hooks. A fact you are unlikely to realize without a hard debugging session. While a simple attribute will suffice with a class.
useRef() in practice behaves almost exactly the same way as instance properties on class-based components, so I think of them as the same thing. useRef is even nicer for debugging IMO because their values are exposed in the React devtools, unlike instance properties.
> spreading accross methods is actually nice: people intertwine code for various steps easily in hooks, making a mess of things
I think having 5 features crammed into the same lifecycle method is far more of a mess than each feature handling their lifecycles independently. That's the point of hooks: you can wrap up functionality that's related to the same feature all in one place. IMO that's simpler to reason about and debug, but I can understand how that might trip other people up. It's sort of horizontal vs. vertical.