But as you can see by the blog post, there are tradeoffs between doing something the way people are familiar with, versus a different way that's less familiar, but has different capabilities that might fit the problems better.
Classes map to certain use cases very well; for instance, there's no Hook for "componentDidCatch" or any other error handling.
That being said, you are not losing anything. The tools are simply different (although the old tools are still there, too!).
As the blog post goes into, you can still implement the same _behavior_ as you did with componentDidMount/componentDidUpdate, but with Hooks you can formalize the different patterns you would find when using those methods into a custom hook that you can reuse. This wasn't possible before.
shouldComponentUpdate can be easily replaced with React.memo, a higher-order component that takes a function that compares the previous props to the new props and returns whether they are the same. Wrapping it in React.memo without a custom comparator is the same as PureComponent.
Guilty as charged. I needed to hear that :)
I mean, as long as hooks are strictly an addition, it's easy to argue greater simplicity without. That's kind of trivial though, so I would ask how thematically related they are.
If they both clearly stem from the same set of underlying principles and motivations, I think it's fair to say the addition is not substantially a complication. But is that the case for hooks? (I don't know—haven't looked into them yet :)
But maybe the confusion is whether the additional complexity we're talking about is in React itself, or in the systems being built with react. In that case, old React may be simpler, but the code it produced was more complicated; or React with hooks may be more complicated, but the code you write with it is now simpler.
Which I (as a proponent of hooks) think is fucking batshit insane, and clearly shows the disconnect of the React devs from their user base.
Teaching beginners how to code, and how to use React, is a large part of my job. And I can say with absolute conviction that the React team is wrong about this. The 'hooks' whiteboarding session has gotten me far more blank stares than the 'classes and lifecycles' one ever has.
Having said that, as a senior dev with a ton of React projects under my belt, I definitely prefer the hooks paradigm after using it in a few projects. It makes for cleaner code, and certain concepts are much easier to reason about with the hooks model. Just don't ever expect it to give you a cleaner on-boarding process. That's not at all where the benefit lies, despite what the docs tell you.
I'd be interested to see how someone who was a beginner but learnt via FP would grasp each approach. I've never met one in the wild though, it's not like bootcamps start with Haskell.
I also never think about “updates”. I do think about rendering as something that happens continuously all the time outside my control.
Hooks, on the other hand, have to be learned as an additional and separate concept. In fact, each hook has to be learned. You won't have a clue what "useState" and "useEffect" do just by having a knowledge of React fundamentals. If using hooks allowed developers to avoid knowing the React component lifecycle, an argument could be made that they provide a simpler alternative, but I don't think anybody is going to get very far without being forced to learn about the component lifecycle. If someone were to say, "The React lifecycle is hard to understand, so use hooks instead," that would be a false promise. Hooks are something extra to learn, not an alternative to understanding the lifecycle. To the extent that a programmer can avoid understanding the lifecycle by using hooks instead, they are just putting off that learning curve until they have to traverse it later, probably under the pressure of debugging some nasty issue.
Hooks seem to win from another perspective, though, which is that by accepting the cost of adding this new concept to your mental model, you can write simpler-looking code that is easier to keep error-free. To me, that's the trade-off. Hooks are an extra complexity to understand, and each new hook can encapsulate arbitrary complexity and behavior that isn't obvious from reading code that uses them, but the code that uses them can be more concise and perhaps easier to read and keep correct.
Let me preface this by saying that I think it's not necessary to conflate the "lifecycle methods" with the component lifecycle in itself, and I disagree with the premise that the methods are a fundamental concept of React. Of course, this is how people were historically taught, but it is entirely possible to conceptualise and understand the lifecycle of a React component without even knowing about lifecycle methods, just in terms of how useEffect works, for instance, and this is how a lot of people using hooks today think. It is entirely possible to understand how re-renderings are triggered and stuff like that without even knowing about class components and lifecycle methods.
So, hooks might seem like an additional concept to people used to class components and lifecycle methods, but that's just because of familiarity. For people learning hooks first, the opposite is true just as well.
IMO this paradigm shift in thinking is also essential for people used to class components that want to be more productive in codebases with mostly hooks. I haven't thought about componentDidUpdate and friends in months.
I would disagree with that premise. From my own experience and from having mentored developers on class components (so like ~7 data points), I'd say it's far easier to reason about state flow with hooks than lifecycle methods. That's an important point, because I see far more bugs with incorrect or incomplete state flow than I see with component lifecycles.
Hooks are simply easier to reason about. With hooks, you read the code top to bottom. Then, something changes either with the data or in response to user input, and then you read the code top to bottom again with that new state.
The only learning curve there is to understanding the basic premise of hooks is that "if this value is different from the last time you read the code top-to-bottom, then re-read/execute this code block"
> If using hooks allowed developers to avoid knowing the React component lifecycle, an argument could be made that they provide a simpler alternative, but I don't think anybody is going to get very far without being forced to learn about the component lifecycle. If someone were to say, "The React lifecycle is hard to understand, so use hooks instead," that would be a false promise.
That is exactly my premise, and I don't think it's a false one. Since moving to hooks, I can't remember the last time I had to care about the React lifecycle. Again, the mental model is "Read the code top to bottom; something changes; read the code from top to bottom" ad infinitum.
Yes there are situations where class components provide more intimate control (componentWillUnmount comes to mind since I'm not aware of a hook for that), but are we really optimizing the majority of our code for exceptional cases?
Another data point: I haven't seen functional components turn into a complete mess from inattentive developers in the same way I've seen class components turn into indecipherable setState tangled messes. The only time I've experienced the pressure of sifting through component lifecycles under the pressure of debugging a time-sensitive production isssue is because I was using component lifecycles in the first place. It's a moot point.
The return value of invoking React.useEffect’s first parameter is a cleanup function which serves this purpose.
Everyone in this thread is ragging on core concepts like useMemo or useEffect. Once you know these core functions, you’ve learned all the magic. Then you can write spells of your own.
>That being said, you are not losing anything. The tools are simply different (although the old tools are still there, too!).
Well... no, you clearly are losing something. You might not use it frequently but it's a pain in the ass when you do need it.
I'd argue it's less important for an API people use every day than it is for an API used once a month. Things should be designed for people with more than one week of experience with it, even if it makes adoption slightly tougher!
We used to fetch data with HOCs. That never worked well with typescript and was a big problem when you wanted to use more than one (ie, fetching multiple data sources). With hooks we just add separate hooks for each data source we fetch... and the hooks themselves are much simpler than HOCs.
Like the article mentions, hooks move up a layer of abstraction. I'm purging my brain of all the nitty gritty detail of React component lifecycles, because all I ever really cared about was getting data to update at the right time. And now that's the level I can operate at.
Yeah, it doesn't look like standard object oriented code that we're used to. Maybe they could have chosen a different syntax, dunno. But after you get used to hooks, the grass definitely is greener.
I specifically talked about these differences in my post "Thoughts on React Hooks, Redux, and Separation of Concerns" [0] and my ReactBoston 2019 talk on "Hooks, HOCs, and Tradeoffs" [1].
For myself personally, I've completely switched to writing function components as a standard practice, but we've also got a lot of devs who are newer to React and still writing classes. I don't feel a need to force rewriting all of those to function components, although I will probably find some time to let folks know that function components + hooks are a thing.
[0] https://blog.isquaredsoftware.com/2019/07/blogged-answers-th...
[1] https://blog.isquaredsoftware.com/2019/09/presentation-hooks...
edit: i guess i'm just supposed to upvote and move on but i'm enthusiastic about this topic :)
The article doesn't show pathological cases using classes, but with hooks it becomes possible to extract complex behaviors involving different lifecycles much more cleanly.
I recently migrated a large React project to use hooks and a lot of repetitive code with lots of repeated patterns (especially things related to data access) is now much more cleaner. Now I can just have something like `useFetch` instead of ten lines of code that I needed just because I was using lifecycle methods.
And the fact that the order of hooks matter is what makes them so easy to abstract. Having them store their own "id" would remove the need for that rule, but then you'd be running at other kinds of bugs.
The order of hooks is only important insofar as they do not change between rendering. That's it. Hooks should always be called, and always in the same order.
A basic React Hooks component has way less boilerplate involved than a class component does, and hooks allow for much better code architecture when it comes to separation of concerns.
Functional components force your component lifecycle into a funnel where the lifecycle becomes obvious, because all the inter-dependencies are already there.
For componentDidMount, you can replicate this easily with hooks:
const Hello = () => {
const mounted = useRef(false)
useEffect(() => {
if (!mounted.current) {
mounted.current = true
console.log("Mounted!");
}
}, [])
return <>Hello</>
}
Extracting anything into a hook is trivial: function useMounted(f) {
const mounted = useRef(false)
useEffect(() => {
if (!mounted.current) {
mounted.current = true
f()
}
}, [])
}
const Hello = () => {
useMounted(() => {
console.log("Mounted!");
})
return <>Hello</>
}
Implementing an unmount callback is also trivial.The useMounted() example, coincidentally, shows a real benefit to hooks: Easy extraction of reusable logic. Hooks are like plugins this way. For example, one hook I've written that I use all the time is this [1], it lets you get a callback every time your component resizes. If you were to do this with a class-based component, you'd have to use an ugly HOC, which results in lots of unnecessary wrapping/nesting.
For componentDidUpdate, useMemo() is arguably easier to deal with.
[1] https://gist.github.com/atombender/b95bbd2014f6a3ec303b843a9...
export const useMounted = (f) => {
useEffect(f, []);
}
Edit: originally: export const useMounted = (f) => {
useEffect(() => {
f();
}, []);
} useEffect(f, [])My main complaint with hooks is people seem to think they always need them. I've seem components where every single piece of data, no matter how trivial, is slapped into a useMemo(). It becomes a lot of mental overhead to trace through them all, especially confirming the useMemos have the correct dependencies specified. Especially when the vast majority of the time, useMemo just isn't needed.
The low level problem here is your team doesn’t realize that every word of code means something.
You need to get past the idea that code has to be there to do a thing and get to the place where you expect every bit of code to explain something.
“Why is there a useMemo here”... if your team can’t explain that, then “changes requested”.
I've seen a lot of cases in the wild where useMemo was used to wrap closures, "for performance reasons", but that's obviously more wasteful than just using the closure by itself. I think a lot of people don't realize that.
That said, you're correct in that this should be the exception and not the rule. It's pointless to do this for a component that returns a single element, as the virtual DOM reconciliation will be much faster than the memoization + props comparison.
I've created a CodePen to illustrate: https://codepen.io/RussianCow/pen/xxbERLL
Open the console and watch as the "render child" message is logged once per second, showing that the child is re-rendered every time the parent is.
But on the other hand I agree that "keep the order!" is a very simple request for a feature that is so useful.
What do you mean?
I have no idea where this is implemented in React, but in Preact it's a simple integer that is incremented:
https://github.com/preactjs/preact/blob/abc162c4d6442d5495f6...
I think there are other ways to implement them, such as treating the return of the render function as an AST and turning hooks into dumb factories, like a free monad. But considering the constraints they have (the need to maintain order) and the way it works (the fact the render function runs multiple times), I'm guessing it's just the same solution as Preact.
With my hooks I've not gotten that visibility but that's probabbly just me getting used to hooks and how to write them better in a way that makes things as clear as the old lifecycle methods.
It doesn't help that I'm bit of a noob as far as web development goes and most examples I look at are pretty straight forward simple apps for teaching the concepts ... but my questions start when things start scaling up.
My complaints about hooks are that with hooks we lose useful tools in our react toolkit: class methods, separate componentDidMount/componentDidUpdate lifecycle events, shouldComponentUpdate, PureComponent, etc.
And my biggest complaint is that we're losing simplicity. React spread like wildfire when it first came out because it was so beautifully simple: a class, with something called `props`, and this.state and this.setState(). That's it. You can build SO MUCH with just that.
To me, with hooks, React's simplicity is being replaced by cloudiness. There's so much "magic" now. The order of hooks in the code is the most important thing for a hook component to work right. New linter rules had to be built to remind people where hooks need to be written.
I do appreciate the work that's been put into hooks. And like any other open source project, I'm incredibly grateful to the authors and maintainers. I guess I just wonder if anyone shares the same sentiments as mine, because it seems like the only thing I read about this topic is that classes suck, class components are full of pitfalls, etc.