From the Development Team

Sep 4, 2019

Learning More About React Hooks

By Paige Willey

Hooks are a little bit controversial on the Underbelly team right now. Some of us are ready to ship, and others are a little more suspicious of trusting precious production code to something so new. Thanks to React Training, we’re feeling a little more confident to include hooks in our everyday React workflow. This isn’t an expose about all the things we learned, because people paid to learn those things! However, here are four hooks we’re using, or getting ready to use, and their most common use cases for the 'Belly team.

  1. useState — Yeah, it’s the simplest one, and yes, we love separating concerns on the Underbelly Team. Sometimes you just need to toggle a navigation dropdown though. No one wants to write an entire render prop for that. Toggling is our most common use case for this hook. We don’t want to make a class-based component for toggling a mobile nav, nor do we want an additional render prop. useState makes it quick and easy for us.
  1. useEffect - I’ve read a lot of things about useEffect, and they are all about as clear as mud. Should I think about it like componentDidMount and componentDidUpdate? Should I not? Is the component lifecycle dead? I’ve certainly seen a number of my peers use this hook in place of those lifecycle functions. As far as I can tell though, useEffect should be treated as its own beast. Here’s what I know for sure: if you think in terms of the dependency array instead of lifecycles, it will become a lot more clear. So much depends on that little array.

Our team works with a lot of data and requesting a lot of data on mount regularly, and I can see that being our most common use-case going forward.

  1. useRef - The 'Belly team recently shipped this one. In the past, refs haven’t been as predictable as we (okay I) would have liked. We used this for a “copy to clipboard” feature, which requires pulling the desired content from a <textarea> defined on a page (if you want it to work in all browsers, that is). In order to achieve this, we used refs on the desired textarea. It worked perfectly.
  1. useContext - We’ve used OG context several times for Underbelly projects (it’s clutch if you’re doing ecomm and need to maintain a cart in several places). For the context hook we recently used it as a means to log user interactions through a site for KPI purposes. This hook felt very familiar to the original context API, and it has made implementation super easy.

If you are interested in leveling up your own React proficiency, check here for upcoming React Training workshops.