Blog Hero Background

Wins for Hooks


User Avatar
Brad WestfallSay hi on Twitter
March 28, 2019
ReactHooks

See Our Public Workshops:

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 this
  • Less complex update strategy vs. componentDidUpdate()

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):

Animating Class-Based component to Hooks-Based Component

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 useScrollPosition.

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.


Instead of having comments here in our blog, we've tweeted about this post so you can comment there if you wish.

View on Twitter

Subscribe for updates on public workshops and blog posts

Don't worry, we don't send emails too often.

i love react
© 2024 ReactTraining.com