chapter seven

7 Hooks to fuel your web applications

 

This chapter covers

  • Creating stateful components in a larger perspective
  • Optimizing performance using memoization
  • 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're going to discuss all the hooks and what they do, cover some important things about using hooks in general, and will at the end talk a bit about the dependency array that several hooks accept and what it means in practice.

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 have 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, and we'll try to tie a bow on it at the end by explaining how all of these hooks are in fact related despite their seemingly divergent purposes.

7.1 Stateful components

7.1.1 Simple state values with useState

7.1.2 Create complex state with useReducer

7.1.3 Remember a value without re-rendering with useRef

7.1.4 Easier multi-component 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 Memoize a component

7.3.2 Memoize part of a component

7.3.3 Memoize properties to memoized components

7.3.4 Memoize any value with useMemo

7.3.5 Memoize functions with useCallback

7.3.6 Create stable DOM identifiers with useId

7.4 Create complex component libraries

7.4.1  Create component APIs with useImperativeHandle

7.4.2 Better debugging of hooks with useDebugValue

7.4.3 Synchronize non-React data with useSyncExternalStore

7.4.4 Run effect before rendering with useInsertionEffect

7.5 The two key principles of hooks