Hooks Revisited

February 16, 2020

Hooks are functions that let you “hook into” React state and lifecycle features from function components [React docs]

Introduced in React v16.8, the hooks API represents a change in how developers compose their components. Intended to compartmentalize blocks of functionality, they make reusing code across your application easier. They also mark a shift away from using class components and the use of lifecycle methods.

When hooks were first introduced at React Conf 2018, the React team explained the motivations behind them. Essentially, they wanted to solve the many problems all at once:

  1. It can be hard to re-use logic between components
  2. Complex component files are huge
  3. Understanding classes in JavaScript can be difficult to understand (for humans and compilers)

For a much more detailed explanation about the origin of hooks, make sure to check out the team's full talk featuring Dan Abramov, Sophie Alpert and Ryan Florence.

Goals

When the hooks API moved out of beta, my team started using them almost immediately. However, most of the logic for the feature I was working on at the time was contained within class components still using lifecycle methods. When creating new components, I was using function components and hooks; however, the components usually weren't complex enough to leverage more than useState or useEffect.

Currently, I work in a codebase that was all written after developers started shifting to hooks and I want to revisit (hence the title of this series) how they all work, as well as when to use them.

To do that, I am writing an article about each standard React hook. Each piece is linked below and will cover the hook in depth, including code samples illustrating how it works.

Table of Contents

  1. useState
  2. useEffect
  3. useLayoutEffect
  4. useRef
  5. useContext
  6. useMemo
  7. useCallback
  8. useReducer
  9. Custom hooks