Skip to content
Brad Westfall

Wins for Hooks

Tags: ReactHooks

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

Animation made with Apple's Keynote

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.

Did you like this content?

We have regularly scheduled public workshops for beginner though advanced topics. All workshops are remote and your company might help you pay for it, just ask! We also conduct corporate trainings if you need more of a personalized experience.

Attend a Public Workshop

While we don't have blog comments, we tweeted about this posting when it went live so we welcome your comments there: