7 Hooks to fuel your web applications

 

This chapter covers

  • A larger perspective on creating stateful components
  • Introducing advanced topics solvable by hooks
  • Rules to observe when using hooks in general

Hooks are what make modern React applications tick. They’re a pretty small part of the overall React API, but very significant nonetheless. Hooks are also quite tricky to use. In this chapter, we’ll discuss all the hooks, what they do, and some important things to know about using hooks in general.

Hooks are a special kind of creature in the React biosphere. From the outside, they seem completely unrelated in functionality, but when examined closer, they have some common traits and behaviors that we need to account for when using them. You could say that they stem from a common ancestor somewhere in the evolutionary tree, even though they have advanced to become very different beings.

We’ve dedicated this chapter to all the hooks for this very reason. So, while we’re going to be covering some wildly different topics, all of them are concerned with using hooks. We’ll tie a bow on it at the end by explaining how all of these hooks are, in fact, related, despite their seemingly divergent purposes.

You’ve seen three different hooks so far: useState (in chapter 5) and useEffect and useLayoutEffect (in chapter 6). At the time of writing, there are 15 built-in hooks in React (as of React 18), which we’ll cover briefly, grouped by their functionality:

7.1 Stateful components

7.1.1 Simple state values with useState

7.1.2 Creating complex state with useReducer

7.1.3 Remembering a value without re-rendering with useRef

7.1.4 Easier multicomponent state with useContext

7.1.5 Low-priority state updates with useDeferredValue and useTransition

7.2 Component effects

7.3 Optimizing performance by minimizing re-rendering

7.3.1 Memoizing any value with useMemo

7.3.2 Memoizing functions with useCallback

7.3.3 Creating stable DOM identifiers with useId

7.4 Creating complex component libraries

7.4.1 Creating component APIs with useImperativeHandle