Skip to content

Wins for Hooks


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.

Loading...

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


React Router

Michael Jackson and Ryan Florence create the React libraries that you use in your apps like React Router and Reach UI. All of our trainers are experts in React and JavaScript so let us share our knowledge with you and your team!

I Love React
© React Training 2019