Now that hooks have been released for... 🤔checks watch ...less than two months, you've probably noticed there are a few obvious wins if you've been using them, like:
- Hooks takes less code to achieve the same thing compared to classes
- No weird issues with
- Less complex update strategy vs.
There are some other wins that might not stand out right away, and one very important win is grouping related code.
Let me explain...
Class-based components encouraged us to group code based on lifecycle methods instead of features. Let's say we want to get a user from the network and we also want to subscribe to a browser window event. With classes, the user-based state is mixed with the window subscription state. The user-based setup is in the same method as the window subscription setup. We didn't need these to be mixed, it's just what we have to do when we group code based on lifecycles.
With hooks we can group code by feature instead (blue for user stuff, green for subscription stuff):
Now with code grouped by feature, it's easy to see that some of our code can be abstracted into a custom hook, like we did in the animation with
Before hooks, we might have used an HoC or a Render Prop pattern to re-use scroll logic. Each of those patterns has well-documented trade-offs but hooks seem to give us the best aspects of these older patterns while avoiding their pitfalls.
That's it. Happy coding.